feat(api): utilise more caching for single-page route

This commit is contained in:
rhld16 2024-12-30 19:59:07 +00:00 committed by nbats
parent 4a6f20c12c
commit 4d4311d312
5 changed files with 1317 additions and 875 deletions

View file

@ -15,8 +15,10 @@
*/
import { fetcher } from 'itty-fetcher'
import { createStorage } from 'unstorage'
import cloudflareKVBindingDriver from 'unstorage/drivers/cloudflare-kv-binding'
// Look inside tbe docs directory
// Look inside the docs directory
const GITHUB_REPO = 'https://api.github.com/repos/fmhy/edit/contents/docs/'
const EXCLUDE_FILES = [
'README.md',
@ -45,6 +47,10 @@ interface File {
}
export default defineEventHandler(async (event) => {
const markdownStorage = createStorage({
driver: cloudflareKVBindingDriver({ binding: 'STORAGE' })
})
let body = '<!-- This is autogenerated content, do not edit manually. -->\n'
const f = fetcher({
headers: {
@ -54,7 +60,13 @@ export default defineEventHandler(async (event) => {
try {
// Fetch the list of files in the repository
const files = await f.get<File[]>(GITHUB_REPO)
const indexCacheKey = "INDEX"
let files = await markdownStorage.getItem<File[]>(indexCacheKey)
if (!files) {
files = await f.get(GITHUB_REPO)
await markdownStorage.setItem(indexCacheKey, files, { ttl: 60 * 60 * 24 * 7 })
}
// Filter out the excluded files and non-markdown files
const markdownFiles = files.filter((file: File) => {
@ -67,12 +79,17 @@ export default defineEventHandler(async (event) => {
return isMarkdownFile && !isExcludedFile && !isInExcludedDirectory
})
// console.info(markdownFiles.map((f) => f.name))
// Fetch and concatenate the contents of the markdown files
// Fetch and concatenate the contents of the markdown files with caching
const contents = await Promise.all(
markdownFiles.map(async (file: File) => {
const cached = await markdownStorage.getItem(file.name)
if (cached) return cached
const content = await f.get<string>(file.download_url)
if (content) {
await markdownStorage.setItem(file.name, content, { ttl: 60 * 60 })
}
return content
})
)
@ -86,6 +103,9 @@ export default defineEventHandler(async (event) => {
}
// biome-ignore lint/correctness/noUndeclaredVariables: <explanation>
appendResponseHeader(event, 'content-type', 'text/markdown;charset=utf-8')
appendResponseHeaders(event, {
'content-type': 'text/markdown;charset=utf-8',
'cache-control': 'public, max-age=3600'
})
return body
})