diff --git a/index.js b/index.js index 05cbec5..35f70a9 100644 --- a/index.js +++ b/index.js @@ -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({ @@ -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) diff --git a/test/index.js b/test/index.js index 0f7bce5..de78cd2 100644 --- a/test/index.js +++ b/test/index.js @@ -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, '') +})