Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,11 @@ const cacheableResponse = ({
Promise.resolve(rawGet(opts)).then(result => {
if (result == null) return undefined
if (typeof result !== 'object') return result
result.etag = getEtag(result)
return result
// Persist createdAt at write time so HIT max-age can count down.
const value = { ...result }
value.etag = getEtag(value)
if (value.createdAt == null) value.createdAt = Date.now()
return value
})

// @keyvhq/memoize only treats forceExpiration === true as a forced refresh.
Expand Down
34 changes: 34 additions & 0 deletions test/ttl.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,37 @@ test('sets default ttl', async t => {
t.true(cacheControl['must-revalidate'])
t.true([86400, 86399].includes(cacheControl['max-age']))
})

test.serial(
'default createdAt is persisted so HIT max-age shrinks',
async t => {
const realNow = Date.now
let now = 1_700_000_000_000
Date.now = () => now
t.teardown(() => {
Date.now = realNow
})

const url = await runServer(
t,
cacheableResponse({
ttl: 3600000,
staleTtl: false,
get: () => ({ data: { foo: 'bar' } }),
send: ({ res }) => {
res.end('Hello World')
}
})
)

const { headers: miss } = await got(`${url}/kikobeats`)
t.is(miss['x-cache-status'], 'MISS')
t.is(parseCacheControl(miss)['max-age'], 3600)

now += 30_000

const { headers: hit } = await got(`${url}/kikobeats`)
t.is(hit['x-cache-status'], 'HIT')
t.is(parseCacheControl(hit)['max-age'], 3570)
}
)