Skip to content

Commit ca08d9b

Browse files
author
Jakub Sarnowski
committed
feat: return 304 when If-None-Match matches ETag
Resolves #31
1 parent 3dc3daf commit ca08d9b

2 files changed

Lines changed: 37 additions & 7 deletions

File tree

index.js

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,13 +99,16 @@ module.exports = ({
9999
} = result
100100

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

103105
debug({
104106
key,
105107
isHit,
106108
cachedResult: !isEmpty(cachedResult),
107109
result: !isEmpty(result),
108-
etag
110+
etag,
111+
ifNoneMatch
109112
})
110113

111114
setHeaders({
@@ -117,13 +120,18 @@ module.exports = ({
117120
hasForce
118121
})
119122

120-
if (!isHit) {
121-
const payload = { etag, createdAt, ttl, data, ...props }
122-
const value = await compress(payload)
123-
await cache.set(key, value, ttl)
123+
if (isModified) {
124+
if (!isHit) {
125+
const payload = { etag, createdAt, ttl, data, ...props }
126+
const value = await compress(payload)
127+
await cache.set(key, value, ttl)
128+
}
129+
130+
return send({ data, res, req, ...props })
131+
} else {
132+
res.statusCode = 304
133+
res.end()
124134
}
125-
126-
return send({ data, res, req, ...props })
127135
}
128136
}
129137

test/index.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,3 +237,25 @@ test('prevent send if data is undefined', async t => {
237237
t.false(isSendCalled)
238238
}
239239
})
240+
241+
test('return empty 304 response when If-None-Match matches ETag', async t => {
242+
const url = await createServer({
243+
get: ({ req, res }) => {
244+
return {
245+
data: { foo: 'bar' },
246+
ttl: 1000,
247+
createdAt: Date.now(),
248+
foo: { bar: true }
249+
}
250+
},
251+
send: ({ data, headers, res, req, ...props }) => {
252+
res.end('Welcome to Micro')
253+
}
254+
})
255+
const { headers } = await got(`${url}/kikobeats`)
256+
const { body, statusCode } = await got(`${url}/kikobeats`, {
257+
headers: { 'If-None-Match': headers.etag }
258+
})
259+
t.is(statusCode, 304)
260+
t.is(body, '')
261+
})

0 commit comments

Comments
 (0)