From a011780f46b93a48893ef7adbde62aeeea3212ea Mon Sep 17 00:00:00 2001
From: Kristian Freeman <kristian@kristianfreeman.com>
Date: Thu, 27 Jul 2023 13:17:36 -0500
Subject: [PATCH] Cache schema using KV (#10083)

* Cache schema using KV

* stringify schema object
---
 functions/schema.js | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/functions/schema.js b/functions/schema.js
index fc1155900..6bb8b8706 100644
--- a/functions/schema.js
+++ b/functions/schema.js
@@ -1,4 +1,11 @@
-export async function onRequestGet() {
+export async function onRequestGet(context) {
+  const cachedSchema = await context.env.API_DOCS_KV.get("schema", "json")
+  if (cachedSchema) {
+    return new Response(JSON.stringify(cachedSchema), {
+      headers: { 'Content-type': 'application/json' }
+    })
+  }
+
   const schemaUrl = "https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.json"
 
   const req = new Request(schemaUrl)
@@ -62,6 +69,9 @@ export async function onRequestGet() {
       response = new Response(JSON.stringify(sortedSchema), {
         headers: { 'Content-type': 'application/json' }
       })
+
+      const expirationTtl = 60 * 60
+      await context.env.API_DOCS_KV.put("schema", JSON.stringify(sortedSchema), { expirationTtl })
     }
 
     return response
-- 
GitLab