Skip to content

Commit c033b79

Browse files
authored
fix: save into cache under 304 response (#43)
* Fixed cache is not saved when response 304 * test: added test case for saving cache after 304 response fix: set ava dependency to version 2.x instead of latest (ava 3.x breaks test cases) * fix: test case should await cache.clear() promise to be fullfilled
1 parent 55eca7a commit c033b79

3 files changed

Lines changed: 33 additions & 7 deletions

File tree

index.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -114,18 +114,18 @@ module.exports = ({
114114
hasForce
115115
})
116116

117-
if (!isModified) {
118-
res.statusCode = 304
119-
res.end()
120-
return
121-
}
122-
123117
if (!isHit) {
124118
const payload = { etag, createdAt, ttl, data, ...props }
125119
const value = await compress(payload)
126120
await cache.set(key, value, ttl)
127121
}
128122

123+
if (!isModified) {
124+
res.statusCode = 304
125+
res.end()
126+
return
127+
}
128+
129129
return send({ data, res, req, ...props })
130130
}
131131
}

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
"devDependencies": {
5757
"@commitlint/cli": "latest",
5858
"@commitlint/config-conventional": "latest",
59-
"ava": "latest",
59+
"ava": "~2.4.0",
6060
"ci-publish": "latest",
6161
"conventional-github-releaser": "latest",
6262
"coveralls": "latest",

test/index.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import listen from 'test-listen'
44
import micro from 'micro'
55
import test from 'ava'
66
import got from 'got'
7+
import Keyv from 'keyv'
78

89
import cacheableResponse from '..'
910

@@ -259,3 +260,28 @@ test('return empty 304 response when If-None-Match matches ETag', async t => {
259260
t.is(statusCode, 304)
260261
t.is(body, '')
261262
})
263+
264+
test('return HIT after empty 304 response', async t => {
265+
const cache = new Keyv({ namespace: 'ssr' })
266+
const url = await createServer({
267+
cache,
268+
get: ({ req, res }) => {
269+
return {
270+
data: { foo: 'bar' },
271+
ttl: 10000,
272+
createdAt: Date.now(),
273+
foo: { bar: true }
274+
}
275+
},
276+
send: ({ data, headers, res, req, ...props }) => {
277+
res.end('Welcome to Micro')
278+
}
279+
})
280+
const { headers: headersOne } = await got(`${url}/kikobeats`)
281+
await cache.clear()
282+
await got(`${url}/kikobeats`, {
283+
headers: { 'If-None-Match': headersOne.etag }
284+
})
285+
const { headers: headersTwo } = await got(`${url}/kikobeats`)
286+
t.is(headersTwo['x-cache-status'], 'HIT')
287+
})

0 commit comments

Comments
 (0)