Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ function fastifyCaching (instance, options, next) {
}

instance.addHook('onRequest', (req, res, next) => {
res.header('Cache-control', value)
if (res.hasHeader('Cache-control') === false) {
res.header('Cache-control', value)
}
next()
})
}
Expand Down
29 changes: 29 additions & 0 deletions test/headers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,35 @@ test('sets public with max-age and s-maxage header', async (t) => {
t.equal(response.headers['cache-control'], 'public, max-age=300, s-maxage=12345')
})

test('do not set headers if another upstream plugin already sets it', async (t) => {
t.plan(2)

const opts = {
privacy: plugin.privacy.PUBLIC,
expiresIn: 300,
serverExpiresIn: 12345
}

const fastify = Fastify()
fastify.addHook('onRequest', async (req, reply) => {
reply.header('cache-control', 'do not override')
})
await fastify.register(plugin, opts)

fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})

await fastify.ready()

const response = await fastify.inject({
method: 'GET',
path: '/'
})
t.ok(response.headers['cache-control'])
t.equal(response.headers['cache-control'], 'do not override')
})

test('only sets max-age and ignores s-maxage with private header', async (t) => {
t.plan(2)

Expand Down