When exporting my pages for my simple static blog site, everything runs smoothly and quickly. However, in development mode, the generation of posts is sluggish and I'm looking to implement caching to speed up the process. I have set up a file called post.ts
where I define my cache as const posts: Post[] = []
.
I anticipate that when running yarn dev
, the post.ts
file will be loaded once allowing me to populate and reuse my cached post array. Strangely, this TypeScript module seems to be loaded multiple times.
import fs from 'fs'
import path from 'path'
// ...
console.log('????? reloading page')
const posts: Post[] = [] // cached posts, hope to generate once
let postsGenerated = false
export async function getSortedPostsData(): Promise<Post[]> {
// Get file names under /posts
const pendings: Promise<any>[] = []
if (postsGenerated) {
console.log('+++++ Using cache ')
return sortPostsByDate(posts)
} else {
console.log('==== Calculating all')
postsGenerated = true
}
let i = 0
traverseDir('content/blog', (path) => {
if (path.includes('.md')) { ... })
}
await Promise.all(pendings)
return sortPostsByDate(posts)
}
Despite my efforts, sometimes the cache is utilized while other times it isn't. Even on consecutive reloads of the same page, the cache usage is inconsistent. Why is this happening? And what steps can be taken to improve the reliability of the caching system?