nitro icon indicating copy to clipboard operation
nitro copied to clipboard

Support dynamic custom cache expiry

Open pi0 opened this issue 2 years ago • 2 comments

Context: https://github.com/unjs/nitro/pull/897 by @harlan-zw (/cc feel free to edit description or put additional comments here)

pi0 avatar Aug 06 '23 20:08 pi0

If this is implemented, will this work?

export default defineCachedEventHandler(async (event) => {
  return {
    asOn: dayjs().format(),
  }
}, {swr: true, 
  maxAge: isBusinessHours() ? 120 : 3600 * 6 ,  // Business hours is from 9AM to 4PM
})

Also, how would we invalidate this cache? If someone requests at 8:30 AM, he will get the cached response for 6 hours, and not updated response from 9AM onwards, which is not the desired case.

ManasMadrecha avatar Oct 13 '23 11:10 ManasMadrecha

I would like to determine maxAge inside a function, e.g.:

const getAccessToken = defineCachedFunction(async () => {
  const data = await fetch<any>('as/iam/authenticate', {
    method: 'POST',
    body: {
      username: uniqaUser,
      password: uniqaPass,
    },
  })
  if (!data.access_token)
    throw new Error('Login failed')

  setCachedMacAge(data.maxAge)
  return data.access_token
}, {
  name: 'uniqaAccessToken',
})

iBobik avatar Mar 04 '24 19:03 iBobik