Skip to content

Commit

Permalink
fix: save into cache under 304 response (#43)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
iKoala authored Feb 19, 2020
1 parent 55eca7a commit c033b79
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 7 deletions.
12 changes: 6 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,18 +114,18 @@ 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)
await cache.set(key, value, ttl)
}

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

return send({ data, res, req, ...props })
}
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
"devDependencies": {
"@commitlint/cli": "latest",
"@commitlint/config-conventional": "latest",
"ava": "latest",
"ava": "~2.4.0",
"ci-publish": "latest",
"conventional-github-releaser": "latest",
"coveralls": "latest",
Expand Down
26 changes: 26 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import listen from 'test-listen'
import micro from 'micro'
import test from 'ava'
import got from 'got'
import Keyv from 'keyv'

import cacheableResponse from '..'

Expand Down Expand Up @@ -259,3 +260,28 @@ test('return empty 304 response when If-None-Match matches ETag', async t => {
t.is(statusCode, 304)
t.is(body, '')
})

test('return HIT after empty 304 response', async t => {
const cache = new Keyv({ namespace: 'ssr' })
const url = await createServer({
cache,
get: ({ req, res }) => {
return {
data: { foo: 'bar' },
ttl: 10000,
createdAt: Date.now(),
foo: { bar: true }
}
},
send: ({ data, headers, res, req, ...props }) => {
res.end('Welcome to Micro')
}
})
const { headers: headersOne } = await got(`${url}/kikobeats`)
await cache.clear()
await got(`${url}/kikobeats`, {
headers: { 'If-None-Match': headersOne.etag }
})
const { headers: headersTwo } = await got(`${url}/kikobeats`)
t.is(headersTwo['x-cache-status'], 'HIT')
})

0 comments on commit c033b79

Please sign in to comment.