├── .npmignore ├── .editorconfig ├── .prettierrc ├── .eslintrc.json ├── .github └── workflows │ ├── ci.yml │ └── npm-publish.yml ├── LICENSE ├── package.json ├── README.md ├── .gitignore ├── index.js └── index.test.js /.npmignore: -------------------------------------------------------------------------------- 1 | .editorconfig 2 | .prettierrc 3 | **/*.test.js 4 | .eslintrc.json 5 | .github 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | insert_final_newline = true 7 | indent_style = space 8 | indent_size = 2 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | "bracketSpacing": false, 4 | "semi": false, 5 | "singleQuote": true, 6 | "printWidth": 80, 7 | "trailingComma": "all", 8 | "overrides": [ 9 | { 10 | "files": ["*.json", ".prettierrc", ".babelrc"], 11 | "options": {"parser": "json"} 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "node": true 4 | }, 5 | "extends": ["standard"], 6 | "rules": { 7 | "comma-dangle": ["error", "always-multiline"], 8 | "eqeqeq": "error", 9 | "no-extra-semi": "error", 10 | "object-curly-spacing": ["error", "never"], 11 | "space-before-function-paren": [ 12 | "error", 13 | {"anonymous": "always", "named": "never", "asyncArrow": "always"} 14 | ] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [10.x, 12.x, 14.x] 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Use Node.js ${{ matrix.node-version }} 24 | uses: actions/setup-node@v1 25 | with: 26 | node-version: ${{ matrix.node-version }} 27 | - run: npm ci 28 | - run: npm run lint 29 | - run: npm run test 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Nguyễn Nhật Hoàng 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages 3 | 4 | name: Release 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - uses: actions/setup-node@v1 16 | with: 17 | node-version: 12 18 | - run: npm ci 19 | - run: npm run lint 20 | - run: npm run test 21 | 22 | publish-npm: 23 | needs: build 24 | runs-on: ubuntu-latest 25 | steps: 26 | - uses: actions/checkout@v2 27 | - uses: actions/setup-node@v1 28 | with: 29 | node-version: 12 30 | registry-url: https://registry.npmjs.org/ 31 | - name: Set output 32 | id: vars 33 | run: echo ::set-output name=release_version::${GITHUB_REF/refs\/tags\//} 34 | - run: npm ci 35 | - run: | 36 | git config --global user.email "hoangnn93@gmail.com" 37 | git config --global user.name "codeaholicguy" 38 | npm publish 39 | env: 40 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 41 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fastify-response-caching", 3 | "version": "0.0.4", 4 | "description": "A Fastify plugin for caching the response", 5 | "main": "index.js", 6 | "husky": { 7 | "hooks": { 8 | "pre-commit": "lint-staged" 9 | } 10 | }, 11 | "lint-staged": { 12 | "**/*.js": [ 13 | "eslint" 14 | ] 15 | }, 16 | "scripts": { 17 | "test": "tap --cov *.test.js", 18 | "lint": "eslint" 19 | }, 20 | "repository": { 21 | "type": "git", 22 | "url": "git+https://github.com/codeaholicguy/fastify-response-caching.git" 23 | }, 24 | "keywords": [ 25 | "fastify", 26 | "fastify-response-caching", 27 | "response-caching", 28 | "caching", 29 | "cache" 30 | ], 31 | "author": "Hoang Nguyen ", 32 | "license": "MIT", 33 | "bugs": { 34 | "url": "https://github.com/codeaholicguy/fastify-response-caching/issues" 35 | }, 36 | "homepage": "https://github.com/codeaholicguy/fastify-response-caching#readme", 37 | "dependencies": { 38 | "fastify-plugin": "^2.3.4", 39 | "keyv": "^4.0.2" 40 | }, 41 | "devDependencies": { 42 | "axios": "^0.20.0", 43 | "eslint": "^7.9.0", 44 | "eslint-config-standard": "^14.1.1", 45 | "eslint-plugin-import": "^2.22.0", 46 | "eslint-plugin-node": "^11.1.0", 47 | "eslint-plugin-promise": "^4.2.1", 48 | "eslint-plugin-standard": "^4.0.1", 49 | "fastify": "^3.4.1", 50 | "husky": "^4.3.0", 51 | "lint-staged": "^10.4.0", 52 | "tap": "^14.10.8" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fastify-response-caching 2 | 3 | ![Node.js CI](https://github.com/codeaholicguy/fastify-response-caching/workflows/Node.js%20CI/badge.svg) 4 | 5 | *fastify-response-caching* is a plugin for the [Fastify](http://fastify.io/) framework 6 | that provides mechanisms for caching response to reduce the server workload. 7 | 8 | By default, this plugin implements caching by request URL (includes all query parameters) 9 | with the caching time (TTL) is 1 seconds. Besides, this plugin also supports additional caching condition 10 | such as request headers. 11 | 12 | ## Example 13 | 14 | This example shows using the plugin to cache response with default options. 15 | 16 | ```js 17 | const fastify = require('fastify') 18 | const fastifyResponseCaching = require('fastify-response-caching') 19 | 20 | fastify.register(fastifyResponseCaching) 21 | ``` 22 | 23 | This example shows using the plugin to cache response with customized caching time. 24 | 25 | ```js 26 | const fastify = require('fastify') 27 | const fastifyResponseCaching = require('fastify-response-caching') 28 | 29 | fastify.register(fastifyResponseCaching, {ttl: 5000}) 30 | ``` 31 | 32 | This example shows using the plugin to cache response with customized caching conditions. 33 | 34 | ```js 35 | const fastify = require('fastify') 36 | const fastifyResponseCaching = require('fastify-response-caching') 37 | 38 | fastify.register(fastifyResponseCaching, {ttl: 5000, headers: ['x-request-agent']}) 39 | ``` 40 | 41 | ## API 42 | 43 | ### Options 44 | 45 | *fastify-response-caching* accepts the options object: 46 | 47 | ```js 48 | { 49 | ttl: 50 | additionalCondition: { 51 | headers: > 52 | } 53 | } 54 | ``` 55 | 56 | + `ttl` (Default: `1000`): a value, in milliseconds, for the lifetime of the response cache. 57 | + `additionalCondition` (Default: `undefined`): a configuration of additional condition for caching. 58 | + `additionalCondition.headers` (Default: `[]`): a list of string, headers that you want to include in the caching condition. 59 | 60 | ## License 61 | 62 | [MIT License](LICENSE) 63 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const fp = require('fastify-plugin') 4 | const Keyv = require('keyv') 5 | const crypto = require('crypto') 6 | const {EventEmitter} = require('events') 7 | 8 | const CACHEABLE_METHODS = ['GET'] 9 | const X_RESPONSE_CACHE = 'x-response-cache' 10 | const X_RESPONSE_CACHE_HIT = 'hit' 11 | const X_RESPONSE_CACHE_MISS = 'miss' 12 | 13 | function isCacheableRequest(req) { 14 | return CACHEABLE_METHODS.includes(req.raw.method) 15 | } 16 | 17 | function buildCacheKey(req, {headers}) { 18 | const {url, headers: requestHeaders} = req.raw 19 | const additionalCondition = headers.reduce((acc, header) => { 20 | return `${acc}__${header}:${requestHeaders[header] || ''}` 21 | }, '') 22 | const data = `${url}__${additionalCondition}` 23 | const encrytedData = crypto.createHash('md5').update(data) 24 | const key = encrytedData.digest('hex') 25 | 26 | return key 27 | } 28 | 29 | function createOnRequestHandler({ttl, additionalCondition: {headers}}) { 30 | return async function handler(req, res) { 31 | if (!isCacheableRequest(req)) { 32 | return 33 | } 34 | 35 | const cache = this.responseCache 36 | const cacheNotifier = this.responseCacheNotifier 37 | const key = buildCacheKey(req, {headers}) 38 | const requestKey = `${key}__requested` 39 | const isRequestExisted = await cache.get(requestKey) 40 | 41 | async function waitForCacheFulfilled(key) { 42 | return new Promise((resolve) => { 43 | cache.get(key).then((cachedString) => { 44 | if (cachedString) { 45 | resolve(cachedString) 46 | } 47 | }) 48 | 49 | const handler = async () => { 50 | const cachedString = await cache.get(key) 51 | 52 | resolve(cachedString) 53 | } 54 | 55 | cacheNotifier.once(key, handler) 56 | 57 | setTimeout(() => cacheNotifier.removeListener(key, handler), ttl) 58 | setTimeout(() => resolve(), ttl) 59 | }) 60 | } 61 | 62 | if (isRequestExisted) { 63 | const cachedString = await waitForCacheFulfilled(key) 64 | 65 | if (cachedString) { 66 | const cached = JSON.parse(cachedString) 67 | res.header(X_RESPONSE_CACHE, X_RESPONSE_CACHE_HIT) 68 | 69 | return res.code(cached.statusCode).header('Content-Type', cached.contentType).send(cached.payload) 70 | } else { 71 | res.header(X_RESPONSE_CACHE, X_RESPONSE_CACHE_MISS) 72 | } 73 | } else { 74 | await cache.set(requestKey, 'cached', ttl) 75 | res.header(X_RESPONSE_CACHE, X_RESPONSE_CACHE_MISS) 76 | } 77 | } 78 | } 79 | 80 | function createOnSendHandler({ttl, additionalCondition: {headers}}) { 81 | return async function handler(req, res, payload) { 82 | if (!isCacheableRequest(req)) { 83 | return 84 | } 85 | 86 | const cache = this.responseCache 87 | const cacheNotifier = this.responseCacheNotifier 88 | const key = buildCacheKey(req, {headers}) 89 | 90 | await cache.set( 91 | key, 92 | JSON.stringify({ 93 | statusCode: res.statusCode, 94 | contentType: res.getHeader('Content-Type'), 95 | payload, 96 | }), 97 | ttl, 98 | ) 99 | cacheNotifier.emit(key) 100 | } 101 | } 102 | 103 | const responseCachingPlugin = ( 104 | instance, 105 | {ttl = 1000, additionalCondition = {}}, 106 | next, 107 | ) => { 108 | const headers = additionalCondition.headers || [] 109 | const opts = {ttl, additionalCondition: {headers}} 110 | const responseCache = new Keyv() 111 | const responseCacheNotifier = new EventEmitter() 112 | 113 | instance.decorate('responseCache', responseCache) 114 | instance.decorate('responseCacheNotifier', responseCacheNotifier) 115 | instance.addHook('onRequest', createOnRequestHandler(opts)) 116 | instance.addHook('onSend', createOnSendHandler(opts)) 117 | 118 | return next() 119 | } 120 | 121 | module.exports = fp(responseCachingPlugin, { 122 | fastify: '3.x', 123 | name: 'fastify-response-caching', 124 | }) 125 | -------------------------------------------------------------------------------- /index.test.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const test = require('tap').test 4 | 5 | const axios = require('axios') 6 | const fastify = require('fastify') 7 | 8 | const plugin = require('./index.js') 9 | 10 | function delay(ms) { 11 | return new Promise((resolve) => setTimeout(resolve, ms)) 12 | } 13 | 14 | test('should decorate cache to fastify instance', (t) => { 15 | t.plan(3) 16 | const instance = fastify() 17 | instance.register(plugin).ready(() => { 18 | t.ok(instance.responseCache) 19 | t.ok(instance.responseCache.set) 20 | t.ok(instance.responseCache.get) 21 | }) 22 | }) 23 | 24 | test('should cache the cacheable request', (t) => { 25 | t.plan(6) 26 | const instance = fastify() 27 | instance.register(plugin, {ttl: 1000}) 28 | instance.get('/cache', (req, res) => { 29 | res.send({hello: 'world'}) 30 | }) 31 | instance.listen(0, async (err) => { 32 | if (err) t.threw(err) 33 | instance.server.unref() 34 | const portNum = instance.server.address().port 35 | const address = `http://127.0.0.1:${portNum}/cache` 36 | const [response1, response2] = await Promise.all([ 37 | axios.get(address), 38 | axios.get(address), 39 | ]) 40 | t.is(response1.status, 200) 41 | t.is(response2.status, 200) 42 | t.is(response1.headers['x-response-cache'], 'miss') 43 | t.is(response2.headers['x-response-cache'], 'hit') 44 | t.deepEqual(response1.data, {hello: 'world'}) 45 | t.deepEqual(response2.data, {hello: 'world'}) 46 | }) 47 | }) 48 | 49 | test('should not cache the uncacheable request', (t) => { 50 | t.plan(6) 51 | const instance = fastify() 52 | instance.register(plugin, {ttl: 1000}) 53 | instance.post('/no-cache', (req, res) => { 54 | res.send({hello: 'world'}) 55 | }) 56 | instance.listen(0, async (err) => { 57 | if (err) t.threw(err) 58 | instance.server.unref() 59 | const portNum = instance.server.address().port 60 | const address = `http://127.0.0.1:${portNum}/no-cache` 61 | const [response1, response2] = await Promise.all([ 62 | axios.post(address, {}), 63 | axios.post(address, {}), 64 | ]) 65 | t.is(response1.status, 200) 66 | t.is(response2.status, 200) 67 | t.notOk(response1.headers['x-response-cache']) 68 | t.notOk(response2.headers['x-response-cache']) 69 | t.deepEqual(response1.data, {hello: 'world'}) 70 | t.deepEqual(response2.data, {hello: 'world'}) 71 | }) 72 | }) 73 | 74 | test('should apply ttl config', (t) => { 75 | t.plan(9) 76 | const instance = fastify() 77 | instance.register(plugin, {ttl: 2000}) 78 | instance.get('/ttl', (req, res) => { 79 | res.send({hello: 'world'}) 80 | }) 81 | instance.listen(0, async (err) => { 82 | if (err) t.threw(err) 83 | instance.server.unref() 84 | const portNum = instance.server.address().port 85 | const address = `http://127.0.0.1:${portNum}/ttl` 86 | const [response1, response2] = await Promise.all([ 87 | axios.get(address), 88 | axios.get(address), 89 | ]) 90 | await delay(3000) 91 | const response3 = await axios.get(address) 92 | t.is(response1.status, 200) 93 | t.is(response2.status, 200) 94 | t.is(response3.status, 200) 95 | t.is(response1.headers['x-response-cache'], 'miss') 96 | t.is(response2.headers['x-response-cache'], 'hit') 97 | t.is(response3.headers['x-response-cache'], 'miss') 98 | t.deepEqual(response1.data, {hello: 'world'}) 99 | t.deepEqual(response2.data, {hello: 'world'}) 100 | t.deepEqual(response3.data, {hello: 'world'}) 101 | }) 102 | }) 103 | 104 | test('should apply additionalCondition config', (t) => { 105 | t.plan(12) 106 | const instance = fastify() 107 | instance.register(plugin, { 108 | additionalCondition: { 109 | headers: ['x-should-applied'], 110 | }, 111 | }) 112 | instance.get('/headers', (req, res) => { 113 | res.send({hello: 'world'}) 114 | }) 115 | instance.listen(0, async (err) => { 116 | if (err) t.threw(err) 117 | instance.server.unref() 118 | const portNum = instance.server.address().port 119 | const address = `http://127.0.0.1:${portNum}/headers` 120 | const [response1, response2, response3, response4] = await Promise.all([ 121 | axios.get(address, { 122 | headers: {'x-should-applied': 'yes'}, 123 | }), 124 | axios.get(address, { 125 | headers: {'x-should-applied': 'yes'}, 126 | }), 127 | axios.get(address, { 128 | headers: {'x-should-applied': 'no'}, 129 | }), 130 | axios.get(address), 131 | ]) 132 | t.is(response1.status, 200) 133 | t.is(response2.status, 200) 134 | t.is(response3.status, 200) 135 | t.is(response4.status, 200) 136 | t.is(response1.headers['x-response-cache'], 'miss') 137 | t.is(response2.headers['x-response-cache'], 'hit') 138 | t.is(response3.headers['x-response-cache'], 'miss') 139 | t.is(response4.headers['x-response-cache'], 'miss') 140 | t.deepEqual(response1.data, {hello: 'world'}) 141 | t.deepEqual(response2.data, {hello: 'world'}) 142 | t.deepEqual(response3.data, {hello: 'world'}) 143 | t.deepEqual(response4.data, {hello: 'world'}) 144 | }) 145 | }) 146 | 147 | test('should waiting for cache if multiple same request come in', (t) => { 148 | t.plan(6) 149 | const instance = fastify() 150 | instance.register(plugin, {ttl: 5000}) 151 | instance.get('/waiting', async (req, res) => { 152 | await delay(3000) 153 | res.send({hello: 'world'}) 154 | }) 155 | instance.listen(0, async (err) => { 156 | if (err) t.threw(err) 157 | instance.server.unref() 158 | const portNum = instance.server.address().port 159 | const address = `http://127.0.0.1:${portNum}/waiting` 160 | const [response1, response2] = await Promise.all([ 161 | axios.get(address), 162 | axios.get(address), 163 | ]) 164 | t.is(response1.status, 200) 165 | t.is(response2.status, 200) 166 | t.is(response1.headers['x-response-cache'], 'miss') 167 | t.is(response2.headers['x-response-cache'], 'hit') 168 | t.deepEqual(response1.data, {hello: 'world'}) 169 | t.deepEqual(response2.data, {hello: 'world'}) 170 | }) 171 | }) 172 | 173 | test('should not waiting for cache due to timeout', (t) => { 174 | t.plan(6) 175 | const instance = fastify() 176 | instance.register(plugin) 177 | instance.get('/abort', async (req, res) => { 178 | await delay(2000) 179 | res.send({hello: 'world'}) 180 | }) 181 | instance.listen(0, async (err) => { 182 | if (err) t.threw(err) 183 | instance.server.unref() 184 | const portNum = instance.server.address().port 185 | const address = `http://127.0.0.1:${portNum}/abort` 186 | const [response1, response2] = await Promise.all([ 187 | axios.get(address), 188 | axios.get(address), 189 | ]) 190 | t.is(response1.status, 200) 191 | t.is(response2.status, 200) 192 | t.is(response1.headers['x-response-cache'], 'miss') 193 | t.is(response2.headers['x-response-cache'], 'miss') 194 | t.deepEqual(response1.data, {hello: 'world'}) 195 | t.deepEqual(response2.data, {hello: 'world'}) 196 | }) 197 | }) 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 | }) 223 | --------------------------------------------------------------------------------