Skip to content

Commit

Permalink
fix: invalidation
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Feb 24, 2019
1 parent 550ce3c commit 1a0e25f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
14 changes: 8 additions & 6 deletions index.js
Expand Up @@ -22,17 +22,19 @@ const getKey = url => {
const toSeconds = ms => Math.floor(ms / 1000)

const createSetCache = ({ revalidate }) => {
return ({ res, createdAt, isHit, ttl, force, etag }) => {
return ({ res, createdAt, isHit, ttl, hasForce, etag }) => {
// Specifies the maximum amount of time a resource
// will be considered fresh in seconds
const diff = force ? 0 : createdAt + ttl - Date.now()
const diff = hasForce ? 0 : createdAt + ttl - Date.now()
const maxAge = toSeconds(diff)

res.setHeader(
'Cache-Control',
`public, max-age=${maxAge}, s-maxage=${maxAge}, stale-while-revalidate=${toSeconds(
revalidate(ttl)
)}`
`public, max-age=${maxAge}, s-maxage=${maxAge}, stale-while-revalidate=${
hasForce ? 0 : toSeconds(revalidate(ttl))
}`
)

res.setHeader('X-Cache-Status', isHit ? 'HIT' : 'MISS')
res.setHeader('X-Cache-Expired-At', prettyMs(diff))
res.setHeader('ETag', etag)
Expand All @@ -54,7 +56,7 @@ module.exports = ({
})

return async ({ req, res, ...opts }) => {
const hasForce = Boolean(req.query ? req.query.force : parse(req.url).force)
const hasForce = Boolean(req.query ? req.query.force : parse(req.url.split('?')[1]).force)
const url = urlResolve('http://localhost', req.url)
const key = getKey(url)
const cachedResult = await cache.get(key)
Expand Down
30 changes: 30 additions & 0 deletions test/index.js
Expand Up @@ -109,6 +109,36 @@ test('HIT for second access', async t => {
t.is(headers['x-cache-status'], 'HIT')
})

test.only('force query params to invalidate', async t => {
const url = await createServer({
get: ({ req, res }) => {
return {
data: { foo: 'bar' },
ttl: 86400000,
createdAt: Date.now(),
foo: { bar: true }
}
},
send: ({ data, headers, res, req, ...props }) => {
res.end('Welcome to Micro')
}
})
const { headers: headersOne } = await got(`${url}/kikobeats`)
t.is(headersOne['x-cache-status'], 'MISS')
t.is(
headersOne['cache-control'],
'public, max-age=86400, s-maxage=86400, stale-while-revalidate=3600'
)
const { headers: headersTwo } = await got(`${url}/kikobeats`)
t.is(headersTwo['x-cache-status'], 'HIT')
const { headers: headersThree } = await got(`${url}/kikobeats?force=true`)
t.is(headersThree['x-cache-status'], 'MISS')
t.is(headersThree['x-cache-expired-at'], '0ms')
t.is(headersThree['cache-control'], 'public, max-age=0, s-maxage=0, stale-while-revalidate=0')
const { headers: headersFour } = await got(`${url}/kikobeats`)
t.is(headersFour['x-cache-status'], 'HIT')
})

test('MISS after cache expiration', async t => {
const url = await createServer({
get: ({ req, res }) => {
Expand Down

0 comments on commit 1a0e25f

Please sign in to comment.