From d71df884a1eac7b8c4d829e16ed804a6f8b15982 Mon Sep 17 00:00:00 2001 From: TheTimmaeh Date: Wed, 21 Jul 2021 21:40:59 +0200 Subject: [PATCH] Delivering original content-type --- index.js | 3 ++- index.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index e26ad75..cb0afb3 100644 --- a/index.js +++ b/index.js @@ -66,7 +66,7 @@ function createOnRequestHandler({ttl, additionalCondition: {headers}}) { const cached = JSON.parse(cachedString) res.header(X_RESPONSE_CACHE, X_RESPONSE_CACHE_HIT) - return res.code(cached.statusCode).send(cached.payload) + return res.code(cached.statusCode).header('Content-Type', cached.contentType).send(cached.payload) } else { res.header(X_RESPONSE_CACHE, X_RESPONSE_CACHE_MISS) } @@ -91,6 +91,7 @@ function createOnSendHandler({ttl, additionalCondition: {headers}}) { key, JSON.stringify({ statusCode: res.statusCode, + contentType: res.getHeader('Content-Type'), payload, }), ttl, diff --git a/index.test.js b/index.test.js index e8bba72..33790a8 100644 --- a/index.test.js +++ b/index.test.js @@ -195,3 +195,28 @@ test('should not waiting for cache due to timeout', (t) => { t.deepEqual(response2.data, {hello: 'world'}) }) }) + +test('should keep the original content type', (t) => { + t.plan(6) + const instance = fastify() + instance.register(plugin, {ttl: 1000}) + instance.get('/contentType', (req, res) => { + res.send({hello: 'world'}) + }) + instance.listen(0, async (err) => { + if (err) t.threw(err) + instance.server.unref() + const portNum = instance.server.address().port + const address = `http://127.0.0.1:${portNum}/contentType` + const [response1, response2] = await Promise.all([ + axios.get(address), + axios.get(address), + ]) + t.is(response1.status, 200) + t.is(response2.status, 200) + t.is(response1.headers['content-type'], 'application/json; charset=utf-8') + t.is(response2.headers['content-type'], 'application/json; charset=utf-8') + t.deepEqual(response1.data, {hello: 'world'}) + t.deepEqual(response2.data, {hello: 'world'}) + }) +})