forked from Mirrors/elk
use cache via nuxt config
This commit is contained in:
parent
f73219f9bd
commit
19c8393c7c
2 changed files with 16 additions and 29 deletions
|
@ -82,6 +82,13 @@ export default defineNuxtConfig({
|
||||||
crawlLinks: false,
|
crawlLinks: false,
|
||||||
routes: ['/', '/200.html'],
|
routes: ['/', '/200.html'],
|
||||||
},
|
},
|
||||||
|
routeRules: {
|
||||||
|
'/api/og-image': {
|
||||||
|
cache: {
|
||||||
|
maxAge: 86400, // 1 day
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
app: {
|
app: {
|
||||||
keepalive: true,
|
keepalive: true,
|
||||||
|
|
|
@ -1,4 +1,9 @@
|
||||||
const inMemoryCache = new Map<string, { url: string; lastUsed: number }>()
|
// 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(/<meta property="og:image" content="([^"]+)" \/>/)
|
||||||
|
return match?.[1] ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
export default defineEventHandler(async (event) => {
|
export default defineEventHandler(async (event) => {
|
||||||
const { cardUrl } = getQuery(event)
|
const { cardUrl } = getQuery(event)
|
||||||
|
@ -17,34 +22,9 @@ export default defineEventHandler(async (event) => {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if (inMemoryCache.has(cardUrl)) {
|
const html = await $fetch<string>(cardUrl)
|
||||||
const { url } = inMemoryCache.get(cardUrl)!
|
const ogImageUrl = extractOgImageUrl(html)
|
||||||
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<string>(cardUrl)
|
|
||||||
let ogImageUrl: string | null | undefined = null
|
|
||||||
|
|
||||||
const match = result.match(/<meta property="og:image" content="([^"]+)" \/>/)
|
|
||||||
ogImageUrl = match?.[1] ?? ''
|
|
||||||
|
|
||||||
inMemoryCache.set(cardUrl, { url: ogImageUrl, lastUsed: Date.now() })
|
|
||||||
|
|
||||||
await send(event, ogImageUrl)
|
await send(event, ogImageUrl)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue