Skip to content

Commit 4f60071

Browse files
authored
Delivering original content-type (#10)
1 parent 503e882 commit 4f60071

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

index.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ function createOnRequestHandler({ttl, additionalCondition: {headers}}) {
6666
const cached = JSON.parse(cachedString)
6767
res.header(X_RESPONSE_CACHE, X_RESPONSE_CACHE_HIT)
6868

69-
return res.code(cached.statusCode).send(cached.payload)
69+
return res.code(cached.statusCode).header('Content-Type', cached.contentType).send(cached.payload)
7070
} else {
7171
res.header(X_RESPONSE_CACHE, X_RESPONSE_CACHE_MISS)
7272
}
@@ -91,6 +91,7 @@ function createOnSendHandler({ttl, additionalCondition: {headers}}) {
9191
key,
9292
JSON.stringify({
9393
statusCode: res.statusCode,
94+
contentType: res.getHeader('Content-Type'),
9495
payload,
9596
}),
9697
ttl,

index.test.js

+25
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,28 @@ test('should not waiting for cache due to timeout', (t) => {
195195
t.deepEqual(response2.data, {hello: 'world'})
196196
})
197197
})
198+
199+
test('should keep the original content type', (t) => {
200+
t.plan(6)
201+
const instance = fastify()
202+
instance.register(plugin, {ttl: 1000})
203+
instance.get('/contentType', (req, res) => {
204+
res.send({hello: 'world'})
205+
})
206+
instance.listen(0, async (err) => {
207+
if (err) t.threw(err)
208+
instance.server.unref()
209+
const portNum = instance.server.address().port
210+
const address = `http://127.0.0.1:${portNum}/contentType`
211+
const [response1, response2] = await Promise.all([
212+
axios.get(address),
213+
axios.get(address),
214+
])
215+
t.is(response1.status, 200)
216+
t.is(response2.status, 200)
217+
t.is(response1.headers['content-type'], 'application/json; charset=utf-8')
218+
t.is(response2.headers['content-type'], 'application/json; charset=utf-8')
219+
t.deepEqual(response1.data, {hello: 'world'})
220+
t.deepEqual(response2.data, {hello: 'world'})
221+
})
222+
})

0 commit comments

Comments
 (0)