From ca08d9b877600fbf2e4c2bb73a041676cd7002c2 Mon Sep 17 00:00:00 2001 From: Jakub Sarnowski Date: Fri, 25 Oct 2019 21:32:22 +0200 Subject: [PATCH 1/2] feat: return 304 when If-None-Match matches ETag Resolves #31 --- index.js | 22 +++++++++++++++------- test/index.js | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/index.js b/index.js index 05cbec5..2cb5cd7 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,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 }) } } 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, '') +}) From 9b54c267e01d071259ff7ffbd70ac218e32086e2 Mon Sep 17 00:00:00 2001 From: Kiko Beats Date: Wed, 30 Oct 2019 18:37:40 +0100 Subject: [PATCH 2/2] refactor: avoid else --- index.js | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index 2cb5cd7..35f70a9 100644 --- a/index.js +++ b/index.js @@ -120,18 +120,19 @@ module.exports = ({ hasForce }) - 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 { + if (!isModified) { res.statusCode = 304 res.end() + return } + + 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 }) } }