From 19c8393c7c5f44dff149d94121c842d1b228aa76 Mon Sep 17 00:00:00 2001 From: Shinigami92 Date: Mon, 12 Dec 2022 14:26:30 +0100 Subject: [PATCH] use cache via nuxt config --- nuxt.config.ts | 7 +++++++ server/api/og-image.ts | 38 +++++++++----------------------------- 2 files changed, 16 insertions(+), 29 deletions(-) diff --git a/nuxt.config.ts b/nuxt.config.ts index bbabadbc..09d70e1b 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -82,6 +82,13 @@ export default defineNuxtConfig({ crawlLinks: false, routes: ['/', '/200.html'], }, + routeRules: { + '/api/og-image': { + cache: { + maxAge: 86400, // 1 day + }, + }, + }, }, app: { keepalive: true, diff --git a/server/api/og-image.ts b/server/api/og-image.ts index 6b97f4fb..566b3805 100644 --- a/server/api/og-image.ts +++ b/server/api/og-image.ts @@ -1,4 +1,9 @@ -const inMemoryCache = new Map() +// This API-Endpoint will be cached via nuxt.config.ts -> nitro.routeRules['/api/og-image'].cache.maxAge = 86400 + +function extractOgImageUrl(html: string): string { + const match = html.match(//) + return match?.[1] ?? '' +} export default defineEventHandler(async (event) => { const { cardUrl } = getQuery(event) @@ -17,34 +22,9 @@ export default defineEventHandler(async (event) => { }) } - if (inMemoryCache.has(cardUrl)) { - const { url } = inMemoryCache.get(cardUrl)! - await send(event, url) - - inMemoryCache.set(cardUrl, { url, lastUsed: Date.now() }) - - // Remove some oldest entries if cache gets to big - if (inMemoryCache.size > 5000) { - // Remove 10% of the oldest entries - const entries = Array.from(inMemoryCache.entries()).sort( - (a, b) => a[1].lastUsed - b[1].lastUsed, - ) - const entriesToRemove = Math.floor(entries.length * 0.1) - - for (let i = 0; i < entriesToRemove; i++) - inMemoryCache.delete(entries[i][0]) - } - - return - } - - const result = await $fetch(cardUrl) - let ogImageUrl: string | null | undefined = null - - const match = result.match(//) - ogImageUrl = match?.[1] ?? '' - - inMemoryCache.set(cardUrl, { url: ogImageUrl, lastUsed: Date.now() }) + const html = await $fetch(cardUrl) + const ogImageUrl = extractOgImageUrl(html) await send(event, ogImageUrl) }) +