1515 */
1616
1717import { fetcher } from 'itty-fetcher'
18+ import { createStorage } from 'unstorage'
19+ import cloudflareKVBindingDriver from 'unstorage/drivers/cloudflare-kv-binding'
1820
19- // Look inside tbe docs directory
21+ // Look inside the docs directory
2022const GITHUB_REPO = 'https://api.github.com/repos/fmhy/edit/contents/docs/'
2123const EXCLUDE_FILES = [
2224 'README.md' ,
@@ -45,6 +47,10 @@ interface File {
4547}
4648
4749export default defineEventHandler ( async ( event ) => {
50+ const markdownStorage = createStorage ( {
51+ driver : cloudflareKVBindingDriver ( { binding : 'STORAGE' } )
52+ } )
53+
4854 let body = '<!-- This is autogenerated content, do not edit manually. -->\n'
4955 const f = fetcher ( {
5056 headers : {
@@ -54,7 +60,13 @@ export default defineEventHandler(async (event) => {
5460
5561 try {
5662 // Fetch the list of files in the repository
57- const files = await f . get < File [ ] > ( GITHUB_REPO )
63+ const indexCacheKey = "INDEX"
64+ let files = await markdownStorage . getItem < File [ ] > ( indexCacheKey )
65+
66+ if ( ! files ) {
67+ files = await f . get ( GITHUB_REPO )
68+ await markdownStorage . setItem ( indexCacheKey , files , { ttl : 60 * 60 * 24 * 7 } )
69+ }
5870
5971 // Filter out the excluded files and non-markdown files
6072 const markdownFiles = files . filter ( ( file : File ) => {
@@ -67,12 +79,17 @@ export default defineEventHandler(async (event) => {
6779 return isMarkdownFile && ! isExcludedFile && ! isInExcludedDirectory
6880 } )
6981
70- // console.info(markdownFiles.map((f) => f.name))
71-
72- // Fetch and concatenate the contents of the markdown files
82+ // Fetch and concatenate the contents of the markdown files with caching
7383 const contents = await Promise . all (
7484 markdownFiles . map ( async ( file : File ) => {
85+ const cached = await markdownStorage . getItem ( file . name )
86+ if ( cached ) return cached
87+
7588 const content = await f . get < string > ( file . download_url )
89+ if ( content ) {
90+ await markdownStorage . setItem ( file . name , content , { ttl : 60 * 60 } )
91+ }
92+
7693 return content
7794 } )
7895 )
@@ -86,6 +103,9 @@ export default defineEventHandler(async (event) => {
86103 }
87104
88105 // biome-ignore lint/correctness/noUndeclaredVariables: <explanation>
89- appendResponseHeader ( event , 'content-type' , 'text/markdown;charset=utf-8' )
106+ appendResponseHeaders ( event , {
107+ 'content-type' : 'text/markdown;charset=utf-8' ,
108+ 'cache-control' : 'public, max-age=3600'
109+ } )
90110 return body
91111} )
0 commit comments