core icon indicating copy to clipboard operation
core copied to clipboard

[Question] Strategy for invalidating cache

Open remihuigen opened this issue 5 months ago • 2 comments

I was wondering about the proper implementation of cache invalidation. Basically, I want to invalidate certain cached functions, when triggering new builds of external apps.

To achieve this I've got this task, which is similar to the Nitro docs: https://nitro.unjs.io/guide/cache#cache-keys-and-invalidation

export default defineTask({
    meta: {
      name: "content:purge",
      description: "Purge all content related cache for a fresh build",
    },
    async run() {
        console.log('purging cache....')

        const cacheKeys = await useStorage('cache').getKeys().then(keys => keys.filter(key => {
          return  key.startsWith('nitro:functions') &&
                  !key.startsWith('nitro:functions:find') &&
                  !key.includes('onderwijsloket') &&
                  !key.includes('Onderwijsloket')
        }))

        cacheKeys.forEach(async key => {
          await useStorage('cache').removeItem(key)
        })

        console.log('✨ cache purge done. ', `Removed ${cacheKeys.length} cached items`)
        return { result: "Success" };
    },
  });

I've also got an api endpoint that programmatically runs this task

export default defineEventHandler({
  onRequest: [
      authTasks
  ],
  handler: async(event) => {
    const { result } = await runTask("content:purge");
    return { result };
  }
})

This works perfectly fine in local dev, but does nothing when running in a CF environment (neither in preview nor production).

Am I missing something here?

remihuigen avatar Sep 17 '24 12:09 remihuigen