unjs / nitro

Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer.
https://nitro.unjs.io
MIT License
5.75k stars 486 forks source link

Support dynamic custom cache expiry #1544

Open pi0 opened 1 year ago

pi0 commented 1 year ago

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

ManasMadrecha commented 10 months ago

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.

iBobik commented 5 months ago

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',
})