From e9bc664668c46c263013bc5859db18054622c9d0 Mon Sep 17 00:00:00 2001 From: dangered wolf Date: Fri, 15 Jul 2022 22:25:32 -0400 Subject: [PATCH] Improved caching logic to hit all requests --- src/server.ts | 46 ++++++++++++++++++++++++++++------------------ 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/src/server.ts b/src/server.ts index 07be12c..e23ecd7 100644 --- a/src/server.ts +++ b/src/server.ts @@ -23,19 +23,8 @@ const statusRequest = async (request: any, event: FetchEvent, flags: Flags = {}) if (isBotUA || flags.direct) { console.log('Matched bot UA'); - // https://developers.cloudflare.com/workers/examples/cache-api/ - const cacheUrl = new URL(request.url); - const cacheKey = new Request(cacheUrl.toString(), request); - const cache = caches.default; - let response = await cache.match(cacheKey); - - if (response) { - console.log('Cache hit'); - return response; - } - - console.log('Cache miss'); + let response: Response; let status = await handleStatus( id.match(/\d{2,20}/)?.[0], @@ -60,11 +49,6 @@ const statusRequest = async (request: any, event: FetchEvent, flags: Flags = {}) }); } - // Store the fetched response as cacheKey - // Use waitUntil so you can return the response without blocking on - // writing to cache - event.waitUntil(cache.put(cacheKey, response.clone())); - return response; } else { console.log('Matched human UA'); @@ -143,9 +127,35 @@ router.all('*', async request => { return Response.redirect(Constants.REDIRECT_URL, 307); }); +const cacheWrapper = async (event: FetchEvent): Promise => { + const { request } = event; + // https://developers.cloudflare.com/workers/examples/cache-api/ + const cacheUrl = new URL(request.url); + const cacheKey = new Request(cacheUrl.toString(), request); + const cache = caches.default; + + let cachedResponse = await cache.match(cacheKey); + + if (cachedResponse) { + console.log('Cache hit'); + return cachedResponse; + } + + console.log('Cache miss'); + + let response = await router.handle(event.request, event); + + // Store the fetched response as cacheKey + // Use waitUntil so you can return the response without blocking on + // writing to cache + event.waitUntil(cache.put(cacheKey, response.clone())); + + return response; +}; + /* Event to receive web requests on Cloudflare Worker */ addEventListener('fetch', (event: FetchEvent) => { - event.respondWith(router.handle(event.request, event)); + event.respondWith(cacheWrapper(event)); });