Skip to content

Commit

Permalink
feat(cache): add support for swr detection (#376)
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux authored Nov 13, 2024
1 parent 0de01aa commit ef5de0d
Showing 1 changed file with 14 additions and 13 deletions.
27 changes: 14 additions & 13 deletions src/runtime/cache/driver.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,31 @@ export default defineDriver((driverOpts) => {
return {
name: 'nuxthub-cache',
...driver,
setItem(key, value, options) {
setItem(key, value, options = {}) {
const event = nitroAsyncContext.tryUse()?.event
// TODO: remove this if once Nitro 2.10 is out with Nuxt version
// As this does not support properly swr (as expiration should not be used)
// Fallback to expires value ({"expires":1729118447040,...})
if (!options.ttl && typeof value === 'string') {
const expires = value.match(/^\{"expires":(\d+),/)?.[1]
let ttl = options.ttl
// If SWR, ttl is not set as options from Nitro
// Guess from expires value ({"expires":1729118447040,...})
if (typeof ttl === 'undefined' && typeof value === 'string') {
const expires = value.match(/[{,]"expires":(\d+)[,}]/)?.[1]
if (expires) {
options.ttl = Math.round((Number(expires) - Date.now()) / 1000)
ttl = Math.round((Number(expires) - Date.now()) / 1000)
}
}
if (options.ttl) {
// Make sure to have a ttl of at least 60 seconds (Cloudflare KV limitation)
options.ttl = Math.max(options.ttl, 60)
}

options.metadata = {
ttl: options.ttl,
ttl,
swr: typeof options.ttl === 'undefined',
mtime: Date.now(),
size: value.length,
path: event?.path,
...options.metadata
}
if (!options.ttl) {
if (options.ttl) {
// Make sure to have a ttl of at least 60 seconds (Cloudflare KV limitation)
options.ttl = Math.max(options.ttl, 60)
} else {
// make sure ttl = 0 is deleted
delete options.ttl
}
return driver.setItem(key, value, options)
Expand Down

0 comments on commit ef5de0d

Please sign in to comment.