Skip to content

Commit 11ff735

Browse files
authored
Handle everything at start of request lifecyle (#23)
1 parent 0fd618c commit 11ff735

File tree

2 files changed

+22
-8
lines changed

2 files changed

+22
-8
lines changed

plugin.js

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,13 @@ function etagHandleRequest (req, res, next) {
3939
})
4040
}
4141

42-
function etagOnSend (fastifyRequest, fastifyReply, payload, next) {
43-
const etag = fastifyReply.getHeader('etag')
44-
if (!etag || !fastifyReply._etagLife) return next()
42+
function etagOnSend (req, res, payload, next) {
43+
const etag = res.getHeader('etag')
44+
if (!etag || !res._etagLife) return next()
4545
this.cache.set(
4646
{ id: etag, segment: this.cacheSegment },
4747
true,
48-
fastifyReply._etagLife,
48+
res._etagLife,
4949
next
5050
)
5151
}
@@ -67,8 +67,8 @@ function fastifyCachingPlugin (instance, options, next) {
6767
value = `${_options.privacy}, max-age=${_options.expiresIn}`
6868
}
6969

70-
instance.addHook('preHandler', (fastifyReq, fastifyReply, next) => {
71-
fastifyReply.header('Cache-control', value)
70+
instance.addHook('onRequest', (req, res, next) => {
71+
res.header('Cache-control', value)
7272
next()
7373
})
7474
}
@@ -81,6 +81,7 @@ function fastifyCachingPlugin (instance, options, next) {
8181
instance.addHook('onRequest', etagHandleRequest)
8282
instance.addHook('onSend', etagOnSend)
8383

84+
instance[Symbol.for('fastify-caching.registered')] = true
8485
next()
8586
}
8687

test/cache.test.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,22 @@ test('cache property gets added to instance', (t) => {
1818
})
1919

2020
test('cache is usable', (t) => {
21-
t.plan(1)
21+
t.plan(3)
2222
const instance = fastify()
23-
instance.register(plugin)
23+
instance
24+
.register((i, o, n) => {
25+
i.addHook('onRequest', function (req, reply, done) {
26+
t.notOk(i[Symbol.for('fastify-caching.registered')])
27+
done()
28+
})
29+
n()
30+
})
31+
.register(plugin)
32+
33+
instance.addHook('preParsing', function (req, reply, done) {
34+
t.is(this[Symbol.for('fastify-caching.registered')], true)
35+
done()
36+
})
2437

2538
instance.get('/one', (req, reply) => {
2639
instance.cache.set('one', { one: true }, 100, (err) => {

0 commit comments

Comments
 (0)