aboutsummaryrefslogtreecommitdiff
path: root/src/fetch-cache.js
diff options
context:
space:
mode:
authorTravis Fischer <[email protected]>2021-06-02 13:59:27 -0400
committerTravis Fischer <[email protected]>2021-06-02 13:59:27 -0400
commitf6321fc3249d83a0059ef47978ed101d3c75375f (patch)
tree9da8b59a0c94c08f92506e57653b8c9f55fa85e8 /src/fetch-cache.js
downloadcf-image-proxy-f6321fc3249d83a0059ef47978ed101d3c75375f.tar.xz
cf-image-proxy-f6321fc3249d83a0059ef47978ed101d3c75375f.zip
feat: import from notion2site repo
Diffstat (limited to 'src/fetch-cache.js')
-rw-r--r--src/fetch-cache.js34
1 files changed, 34 insertions, 0 deletions
diff --git a/src/fetch-cache.js b/src/fetch-cache.js
new file mode 100644
index 0000000..3fb6830
--- /dev/null
+++ b/src/fetch-cache.js
@@ -0,0 +1,34 @@
+const cache = caches.default
+
+export async function fetchCache(opts) {
+ const { event, cacheKey, fetch: fetchResponse } = opts
+
+ let response
+
+ if (cacheKey) {
+ console.log('cacheKey', cacheKey.url)
+ response = await cache.match(cacheKey)
+ }
+
+ if (!response) {
+ response = await fetchResponse()
+ response = new Response(response.body, response)
+
+ if (cacheKey) {
+ if (response.headers.has('Cache-Control')) {
+ // cache will respect response headers
+ event.waitUntil(
+ cache.put(cacheKey, response.clone()).catch((err) => {
+ console.warn('cache put error', cacheKey, err)
+ })
+ )
+ }
+
+ response.headers.set('cf-cache-status', 'MISS')
+ } else {
+ response.headers.set('cf-cache-status', 'BYPASS')
+ }
+ }
+
+ return response
+}