Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't override cache-control if it has already been set #122

Merged
merged 4 commits into from
Mar 28, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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')) {
prevostc marked this conversation as resolved.
Show resolved Hide resolved
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