Skip to content

Commit

Permalink
feat: return 304 when If-None-Match matches ETag (#32)
Browse files Browse the repository at this point in the history
feat: return 304 when If-None-Match matches ETag
  • Loading branch information
Kikobeats committed Oct 30, 2019
2 parents ca144ac + 9b54c26 commit ef672a1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
11 changes: 10 additions & 1 deletion 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,6 +120,12 @@ module.exports = ({
hasForce
})

if (!isModified) {
res.statusCode = 304
res.end()
return
}

if (!isHit) {
const payload = { etag, createdAt, ttl, data, ...props }
const value = await compress(payload)
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 ef672a1

Please sign in to comment.