| 4 | |
| 5 | /* Wrapper to handle caching */ |
| 6 | export const cacheMiddleware = (): MiddlewareHandler => async (c, next) => { |
| 7 | const request = c.req; |
| 8 | const userAgent = request.header('User-Agent') ?? ''; |
| 9 | // https://developers.cloudflare.com/workers/examples/cache-api/ |
| 10 | let cacheUrl = new URL(request.url); |
| 11 | |
| 12 | // Disable caching for Discord for now because of https://github.com/FxEmbed/FxEmbed/issues/2025 |
| 13 | if (userAgent.includes('Discordbot') || userAgent.includes('Firefox/92')) { |
| 14 | return await next(); |
| 15 | } |
| 16 | |
| 17 | /* User agents that include both Telegram and Discord should not be cached |
| 18 | since our response would contain quirks of both platforms. */ |
| 19 | if (userAgent.includes('TelegramBot') && userAgent.includes('Discordbot')) { |
| 20 | console.log('User agent includes both Telegram and Discord, skipping cache'); |
| 21 | return await next(); |
| 22 | } else if (userAgent.includes('TelegramBot')) { |
| 23 | cacheUrl = new URL(`${request.url}&telegram`); |
| 24 | } else if (userAgent.includes('Discordbot')) { |
| 25 | cacheUrl = new URL(`${request.url}&discord`); |
| 26 | } else if (userAgent.match(Constants.NATIVE_MULTI_IMAGE_UA_REGEX)) { |
| 27 | cacheUrl = new URL(`${request.url}&multibot`); |
| 28 | } else if (userAgent.match(Constants.BOT_UA_REGEX)) { |
| 29 | cacheUrl = new URL(`${request.url}&bot`); |
| 30 | } |
| 31 | |
| 32 | console.log('cacheUrl', cacheUrl); |
| 33 | |
| 34 | // Ignore caching on workers.dev, localhost, and 127.0.0.1 |
| 35 | if ( |
| 36 | cacheUrl.hostname.includes('workers.dev') || |
| 37 | cacheUrl.hostname.includes('localhost') || |
| 38 | cacheUrl.hostname.includes('127.0.0.1') |
| 39 | ) { |
| 40 | return await next(); |
| 41 | } |
| 42 | |
| 43 | let cacheKey: Request; |
| 44 | const apiRealmHost = |
| 45 | Constants.API_HOST_LIST.includes(cacheUrl.hostname) || |
| 46 | Constants.BLUESKY_API_HOST_LIST.includes(cacheUrl.hostname) || |
| 47 | Constants.ATMOSPHERE_API_HOST_LIST.includes(cacheUrl.hostname); |
| 48 | const returnAsJson = apiRealmHost; |
| 49 | const skipReadThroughCache = apiRealmHost; |
| 50 | |
| 51 | /* If caching unavailable, ignore the rest of the cache middleware */ |
| 52 | if (typeof caches === 'undefined') { |
| 53 | return await next(); |
| 54 | } |
| 55 | |
| 56 | try { |
| 57 | cacheKey = new Request(cacheUrl.toString(), request); |
| 58 | } catch (_e) { |
| 59 | /* In Miniflare, you can't really create requests like this, so we ignore caching in the test environment */ |
| 60 | return await next(); |
| 61 | } |
| 62 | |
| 63 | const cache = caches.default; |