Skip to content

Commit

Permalink
feat: return 304 when If-None-Match matches ETag
Browse files Browse the repository at this point in the history
Resolves #31
  • Loading branch information
Jakub Sarnowski committed Oct 25, 2019
1 parent 3dc3daf commit ca08d9b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 7 deletions.
22 changes: 15 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,16 @@ module.exports = ({
} = result

const etag = cachedEtag || getEtag(serialize(data))
const ifNoneMatch = req.headers['if-none-match']
const isModified = etag !== ifNoneMatch

debug({
key,
isHit,
cachedResult: !isEmpty(cachedResult),
result: !isEmpty(result),
etag
etag,
ifNoneMatch
})

setHeaders({
Expand All @@ -117,13 +120,18 @@ module.exports = ({
hasForce
})

if (!isHit) {
const payload = { etag, createdAt, ttl, data, ...props }
const value = await compress(payload)
await cache.set(key, value, ttl)
if (isModified) {
if (!isHit) {
const payload = { etag, createdAt, ttl, data, ...props }
const value = await compress(payload)
await cache.set(key, value, ttl)
}

return send({ data, res, req, ...props })
} else {
res.statusCode = 304
res.end()
}

return send({ data, res, req, ...props })
}
}

Expand Down
22 changes: 22 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,25 @@ test('prevent send if data is undefined', async t => {
t.false(isSendCalled)
}
})

test('return empty 304 response when If-None-Match matches ETag', async t => {
const url = await createServer({
get: ({ req, res }) => {
return {
data: { foo: 'bar' },
ttl: 1000,
createdAt: Date.now(),
foo: { bar: true }
}
},
send: ({ data, headers, res, req, ...props }) => {
res.end('Welcome to Micro')
}
})
const { headers } = await got(`${url}/kikobeats`)
const { body, statusCode } = await got(`${url}/kikobeats`, {
headers: { 'If-None-Match': headers.etag }
})
t.is(statusCode, 304)
t.is(body, '')
})

0 comments on commit ca08d9b

Please sign in to comment.