CedsTrash
CedsTrash
NNuxt
Created by CedsTrash on 8/22/2024 in #❓・help
defineCachedEventHandler - set maxAge from environment variable
Hi everyone, I'm trying to figure out how to set my maxAge value from my config because I want it to be different in staging vs production:
export default defineCachedEventHandler(async (event) => {
const config = useRuntimeConfig()

const body = await readBody(event)

let url = config.public.BASE_API_URL + '/collections/' + body.type + '/entries?filter[site]=' + body.locale + '&filter[url]=' + body.url
if ('previewToken' in body) {
url += '&token=' + body.previewToken
}
const result = await $fetch(url)

return {
data: result.data,
fetchedAt: new Date()
}
}, {
maxAge: 1, // Change back to 30
swr: false,
shouldBypassCache: async (event) => {
const body = await readBody(event)
return 'previewToken' in body
},
getKey: async (event) => {
const body = await readBody(event)

return body.cacheKey
}
})
export default defineCachedEventHandler(async (event) => {
const config = useRuntimeConfig()

const body = await readBody(event)

let url = config.public.BASE_API_URL + '/collections/' + body.type + '/entries?filter[site]=' + body.locale + '&filter[url]=' + body.url
if ('previewToken' in body) {
url += '&token=' + body.previewToken
}
const result = await $fetch(url)

return {
data: result.data,
fetchedAt: new Date()
}
}, {
maxAge: 1, // Change back to 30
swr: false,
shouldBypassCache: async (event) => {
const body = await readBody(event)
return 'previewToken' in body
},
getKey: async (event) => {
const body = await readBody(event)

return body.cacheKey
}
})
I would like to set maxAge to config.NITRO_CACHE_TTL but since it expects a number I can't use a function. Would someone know how to do achieve this? Thanks.
9 replies