express-response-middleware 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,28 @@
1
+ name: Publish Package to npmjs
2
+ on:
3
+ push:
4
+ branches:
5
+ - main
6
+
7
+ permissions:
8
+ contents: write
9
+ pull-requests: write
10
+
11
+ jobs:
12
+ release-please:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-node@v4
17
+ with:
18
+ node-version-file: '.node-version'
19
+ - uses: pnpm/action-setup@v4
20
+ name: Install pnpm
21
+ - uses: googleapis/release-please-action@v4
22
+ id: release
23
+ with:
24
+ release-type: node
25
+ - run: 'echo "//registry.npmjs.org/:_authToken=${{secrets.NPM_TOKEN}}" > ~/.npmrc'
26
+ if: ${{ steps.release.outputs.release_created }}
27
+ - run: pnpm publish --no-git-checks
28
+ if: ${{ steps.release.outputs.release_created }}
@@ -0,0 +1,56 @@
1
+ name: Test
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ pull_request:
8
+ branches:
9
+ - main
10
+
11
+ jobs:
12
+ run-lint:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - name: Checkout code
16
+ uses: actions/checkout@v4
17
+ with:
18
+ fetch-depth: 0
19
+
20
+ - name: Install pnpm
21
+ uses: pnpm/action-setup@v4
22
+
23
+ - name: Setup node version
24
+ uses: actions/setup-node@v4
25
+ with:
26
+ node-version-file: '.node-version'
27
+ cache: 'pnpm'
28
+
29
+ - name: Install dependencies
30
+ run: pnpm i --frozen-lockfile
31
+
32
+ - name: Lint format
33
+ run: pnpm lint:format
34
+
35
+ run-test:
36
+ runs-on: ubuntu-latest
37
+ steps:
38
+ - name: Checkout code
39
+ uses: actions/checkout@v4
40
+ with:
41
+ fetch-depth: 0
42
+
43
+ - uses: pnpm/action-setup@v4
44
+ name: Install pnpm
45
+
46
+ - name: Setup node version
47
+ uses: actions/setup-node@v4
48
+ with:
49
+ node-version-file: '.node-version'
50
+ cache: 'pnpm'
51
+
52
+ - name: Install dependencies
53
+ run: pnpm i --frozen-lockfile
54
+
55
+ - name: Test Code
56
+ run: pnpm test
package/.node-version ADDED
@@ -0,0 +1 @@
1
+ 22
@@ -0,0 +1,8 @@
1
+ {
2
+ "singleQuote": true,
3
+ "tabWidth": 2,
4
+ "semi": false,
5
+ "trailingComma": "es5",
6
+ "bracketSpacing": true,
7
+ "arrowParens": "avoid"
8
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 (2025-03-03)
4
+
5
+
6
+ ### Features
7
+
8
+ * **mung:** option to allow munging of JSON errors, fixes [#7](https://github.com/marklai1998/express-response-middleware/issues/7) ([fa1b802](https://github.com/marklai1998/express-response-middleware/commit/fa1b8025aa2267d256e90d4143de3ea6e8a85a03))
9
+ * tests and better implementation for writeJson ([5369d3d](https://github.com/marklai1998/express-response-middleware/commit/5369d3d02848ac3c5031c75f530eef64d226c822))
10
+
11
+
12
+ ### Bug Fixes
13
+
14
+ * args is not set ([031b0eb](https://github.com/marklai1998/express-response-middleware/commit/031b0ebde37f999295e7d2fa543933af13d5c27d))
15
+ * missing option change ([bcf292a](https://github.com/marklai1998/express-response-middleware/commit/bcf292a7e00b328757ce88f60282080bbf1a499d))
16
+ * remove mung names from public api ([c341e79](https://github.com/marklai1998/express-response-middleware/commit/c341e799d8026c60d888ce193f2660e7e1d30e09))
17
+ * returning a scalar number [#22](https://github.com/marklai1998/express-response-middleware/issues/22) ([dc57062](https://github.com/marklai1998/express-response-middleware/commit/dc5706214b62643893361e33fdb07075f549d402))
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Richard Schneider
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
+
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # express-response-middleware
2
+
3
+ Middleware for express responses.
4
+
5
+ This package allows synchronous and asynchronous transformation of an express response. This is a similar concept to the express middleware for a request but for a response. Note that the middleware is executed in LIFO order. It is implemented by monkey patching (hooking) the `res.end`, `res.json`, or `res.write` methods.
6
+
7
+ ## Getting started [![npm version](https://badge.fury.io/js/express-response-middleware.svg)](https://badge.fury.io/js/express-response-middleware)
8
+
9
+ $ npm install express-response-middleware --save
10
+
11
+ Then in your middleware
12
+
13
+ var responseMiddleware = require('express-response-middleware');
14
+
15
+ module.exports = responseMiddleware.json(my_transform);
16
+
17
+ ## Usage
18
+
19
+ Sample middleware (redact.js) to remove classified information.
20
+
21
+ ```javascript
22
+ 'use strict'
23
+ const responseMiddleware = require('express-response-middleware')
24
+
25
+ /* Remove any classified information from the response. */
26
+ function redact(body, req, res) {
27
+ if (body.secret) body.secret = '****'
28
+ // ...
29
+ return body
30
+ }
31
+
32
+ module.exports = responseMiddleware.json(redact)
33
+ ```
34
+
35
+ then add to your `app.js` file (before the route handling middleware)
36
+
37
+ ```javascript
38
+ app.use(require('./redact'))
39
+ ```
40
+
41
+ and [_That's all folks!_](https://www.youtube.com/watch?v=gBzJGckMYO4)
42
+
43
+ See the mocha [tests](https://github.com/marklai1998/express-response-middleware/tree/master/test) for some more examples.
44
+
45
+ ## Reference
46
+
47
+ ### responseMiddleware.json(fn, [options])
48
+
49
+ Transform the JSON body of the response.
50
+
51
+ `fn(json, req, res)` receives the JSON as an object, the `req` and `res`. It returns the modified body. If `undefined` is returned (i.e. nothing) then the original JSON is assumed to be modified. If `null` is returned, then a 204 No Content HTTP status is returned to client.
52
+
53
+ ### responseMiddleware.jsonAsync(fn, [options])
54
+
55
+ Asynchronously transform the JSON body of the response.
56
+
57
+ `fn(json, req, res)` receives the JSON as an object, the `req` and `res`. It returns a promise to a modified body. The promise returns an `object.` If it is `null` then a 204 No Content is sent to the client.
58
+
59
+ ### responseMiddleware.headers(fn)
60
+
61
+ Transform the HTTP headers of the response.
62
+
63
+ `fn(req, res)` receives the `req` and `res`. It should modify the header(s) and then return.
64
+
65
+ ### responseMiddleware.headersAsync(fn)
66
+
67
+ Asynchronously transform the HTTP headers of the response.
68
+
69
+ `fn(req, res)` receives the `req` and `res`. It returns a `promise` to modify the header(s).
70
+
71
+ ### responseMiddleware.write(fn, [options])
72
+
73
+ `fn(chunk, encoding, req, res)` receives the string or buffer as `chunk`, its `encoding` if applicable (`null` otherwise), `req` and `res`. It returns the modified body. If `undefined` is returned (i.e. nothing) then the original unmodified chunk is used.
74
+
75
+ ### Notes
76
+
77
+ - when `responseMiddleware.json*` receives a scalar value then the `content-type` is switched `text-plain`.
78
+
79
+ - when `responseMiddleware.json*` detects that a response has been sent, it will abort.
80
+
81
+ - sending a response while in `responseMiddleware.headers*` is **undefined behaviour** and will most likely result in an error.
82
+
83
+ - when `responseMiddleware.write` detects that a response has completed (i.e. if `res.end` has been called), it will abort.
84
+
85
+ - calling `res.json` or `res.send` from `responseMiddleware.write` can lead to unexpected behavior since they end the response internally.
86
+
87
+ ### options
88
+
89
+ - `runOnError`, when `true` the callback function is always invoked. When `false` (the default) the callback function is only invoked when the response is not in error.
90
+
91
+ ## Exception handling
92
+
93
+ `responseMiddleware` catches any exception (synchronous, asynchronous or Promise reject) and sends an HTTP 500 response with the exception message. You should handle your own error if you want different behavior
94
+
95
+ ## Migrate from `express-mung`
96
+
97
+ - Update the import
98
+ - Rename option `mungError` to `runOnError`
99
+ - Add try catch to your function body if used to override mung.onError()
100
+
101
+ ```
102
+ - import mung from 'express-mung'
103
+ + import mung from 'express-mung'
104
+
105
+ const myMiddleware = mung.json(() => {
106
+ // code here
107
+ },
108
+ - { mungError: true }
109
+ + { runOnError: true }
110
+ )
111
+ ```
112
+
113
+ # License
114
+
115
+ The MIT license
package/index.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ /// <reference types="node"/>
2
+
3
+ import { ErrorRequestHandler, Request, RequestHandler, Response } from 'express'
4
+
5
+ export type Transform = (body: {}, request: Request, response: Response) => any
6
+ export type TransformAsync = (
7
+ body: {},
8
+ request: Request,
9
+ response: Response
10
+ ) => PromiseLike<any>
11
+ export type TransformHeader = (request: Request, response: Response) => any
12
+ export type TransformHeaderAsync = (
13
+ request: Request,
14
+ response: Response
15
+ ) => PromiseLike<any>
16
+ export type TransformChunk = (
17
+ chunk: string | Buffer,
18
+ encoding: string | null,
19
+ request: Request,
20
+ response: Response
21
+ ) => string | Buffer
22
+
23
+ export interface Options {
24
+ runOnError: boolean
25
+ }
26
+
27
+ /**
28
+ * Transform the JSON body of the response.
29
+ * @param fn A transformation function.
30
+ * @param options json options.
31
+ * @return Middleware to transform the body
32
+ */
33
+ export function json(fn: Transform, options?: Options): RequestHandler
34
+
35
+ /**
36
+ * Asynchronously transform the JSON body of the response.
37
+ * @param fn A transformation function.
38
+ * @param options jsonAsync options.
39
+ * @return Middleware to transform the body
40
+ */
41
+ export function jsonAsync(fn: TransformAsync, options?: Options): RequestHandler
42
+
43
+ /**
44
+ * Transform the HTTP headers of the response.
45
+ * @param fn A transformation function.
46
+ * @return Middleware to transform the headers
47
+ */
48
+ export function headers(fn: TransformHeader): RequestHandler
49
+
50
+ /**
51
+ * Asynchronously transform the HTTP headers of the response.
52
+ * @param fn A transformation function.
53
+ * @return Middleware to transform the headers
54
+ */
55
+ export function headersAsync(fn: TransformHeaderAsync): RequestHandler
56
+
57
+ /**
58
+ * Transform chunks as they are written to the response
59
+ * @param fn A transformation function.
60
+ * @param options Write options.
61
+ * @return Middleware to transform chunks.
62
+ */
63
+ export function write(fn: TransformChunk, options?: Options): RequestHandler
64
+
65
+ /**
66
+ * Override the default onError handler.
67
+ * @see {ErrorRequestHandler}
68
+ */
69
+ export let onError: ErrorRequestHandler
package/index.js ADDED
@@ -0,0 +1,203 @@
1
+ 'use strict'
2
+
3
+ let responseMiddleware = {}
4
+ let faux_fin = { end: () => null }
5
+
6
+ function isScalar(v) {
7
+ return typeof v !== 'object' && !Array.isArray(v)
8
+ }
9
+
10
+ responseMiddleware.onError = (err, req, res, next) => {
11
+ res
12
+ .status(500)
13
+ .set('content-language', 'en')
14
+ .json({ message: err.message })
15
+ .end()
16
+ return res
17
+ }
18
+
19
+ responseMiddleware.json = function json(fn, options) {
20
+ return function (req, res, next) {
21
+ let original = res.json
22
+ options = options || {}
23
+ let runOnError = options.runOnError
24
+
25
+ function json_hook(json) {
26
+ let originalJson = json
27
+ res.json = original
28
+ if (res.headersSent) return res
29
+ if (!runOnError && res.statusCode >= 400) return original.call(this, json)
30
+
31
+ // Run the munger
32
+ try {
33
+ json = fn(json, req, res)
34
+ } catch (e) {
35
+ return responseMiddleware.onError(e, req, res, next)
36
+ }
37
+ if (res.headersSent) return res
38
+
39
+ // If no returned value from fn, then assume json has been mucked with.
40
+ if (json === undefined) json = originalJson
41
+
42
+ // If null, then 204 No Content
43
+ if (json === null) return res.status(204).end()
44
+
45
+ // If munged scalar value, then text/plain
46
+ if (originalJson !== json && isScalar(json)) {
47
+ res.set('content-type', 'text/plain')
48
+ return res.send(String(json))
49
+ }
50
+
51
+ return original.call(this, json)
52
+ }
53
+ res.json = json_hook
54
+
55
+ next && next()
56
+ }
57
+ }
58
+
59
+ responseMiddleware.jsonAsync = function json(fn, options) {
60
+ return function (req, res, next) {
61
+ let original = res.json
62
+ options = options || {}
63
+ let runOnError = options.runOnError
64
+
65
+ function json_async_hook(json) {
66
+ let originalJson = json
67
+ res.json = original
68
+ if (res.headersSent) return
69
+ if (!runOnError && res.statusCode >= 400) return original.call(this, json)
70
+ try {
71
+ fn(json, req, res)
72
+ .then(json => {
73
+ if (res.headersSent) return
74
+
75
+ // If null, then 204 No Content
76
+ if (json === null) return res.status(204).end()
77
+
78
+ // If munged scalar value, then text/plain
79
+ if (json !== originalJson && isScalar(json)) {
80
+ res.set('content-type', 'text/plain')
81
+ return res.send(String(json))
82
+ }
83
+
84
+ return original.call(this, json)
85
+ })
86
+ .catch(e => responseMiddleware.onError(e, req, res, next))
87
+ } catch (e) {
88
+ responseMiddleware.onError(e, req, res, next)
89
+ }
90
+
91
+ return faux_fin
92
+ }
93
+ res.json = json_async_hook
94
+
95
+ next && next()
96
+ }
97
+ }
98
+
99
+ responseMiddleware.headers = function headers(fn) {
100
+ return function (req, res, next) {
101
+ let original = res.end
102
+ function headers_hook() {
103
+ res.end = original
104
+ if (!res.headersSent) {
105
+ try {
106
+ fn(req, res)
107
+ } catch (e) {
108
+ return responseMiddleware.onError(e, req, res, next)
109
+ }
110
+ if (res.headersSent) {
111
+ console.error(
112
+ 'sending response while in mung.headers is undefined behaviour'
113
+ )
114
+ return
115
+ }
116
+ }
117
+ return original.apply(this, arguments)
118
+ }
119
+ res.end = headers_hook
120
+
121
+ next && next()
122
+ }
123
+ }
124
+
125
+ responseMiddleware.headersAsync = function headersAsync(fn) {
126
+ return function (req, res, next) {
127
+ let original = res.end
128
+ let onError = e => {
129
+ res.end = original
130
+ return responseMiddleware.onError(e, req, res, next)
131
+ }
132
+ function headers_async_hook() {
133
+ let args = arguments
134
+ if (res.headersSent) return original.apply(this, args)
135
+ res.end = () => null
136
+ try {
137
+ fn(req, res)
138
+ .then(() => {
139
+ res.end = original
140
+ if (res.headersSent) return
141
+ original.apply(this, args)
142
+ })
143
+ .catch(e => onError(e, req, res, next))
144
+ } catch (e) {
145
+ onError(e, req, res, next)
146
+ }
147
+ }
148
+ res.end = headers_async_hook
149
+
150
+ next && next()
151
+ }
152
+ }
153
+
154
+ responseMiddleware.write = function write(fn, options = {}) {
155
+ return function (req, res, next) {
156
+ const original = res.write
157
+ const runOnError = options.runOnError
158
+
159
+ function write_hook(chunk, encoding, callback) {
160
+ // If res.end has already been called, do nothing.
161
+ if (res.finished) {
162
+ return false
163
+ }
164
+
165
+ // Do not mung on errors
166
+ if (!runOnError && res.statusCode >= 400) {
167
+ return original.apply(res, arguments)
168
+ }
169
+
170
+ try {
171
+ let modifiedChunk = fn(
172
+ chunk,
173
+ // Since `encoding` is an optional argument to `res.write`,
174
+ // make sure it is a string and not actually the callback.
175
+ typeof encoding === 'string' ? encoding : null,
176
+ req,
177
+ res
178
+ )
179
+
180
+ // res.finished is set to `true` once res.end has been called.
181
+ // If it is called in the mung function, stop execution here.
182
+ if (res.finished) {
183
+ return false
184
+ }
185
+
186
+ // If no returned value from fn, then set it back to the original value
187
+ if (modifiedChunk === undefined) {
188
+ modifiedChunk = chunk
189
+ }
190
+
191
+ return original.call(res, modifiedChunk, encoding, callback)
192
+ } catch (err) {
193
+ return responseMiddleware.onError(err, req, res, next)
194
+ }
195
+ }
196
+
197
+ res.write = write_hook
198
+
199
+ next && next()
200
+ }
201
+ }
202
+
203
+ module.exports = responseMiddleware
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "express-response-middleware",
3
+ "version": "1.0.0",
4
+ "description": "Transform an express response (or make until no good)",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/marklai1998/express-response-middleware"
10
+ },
11
+ "keywords": [
12
+ "mung",
13
+ "middleware",
14
+ "transform",
15
+ "response",
16
+ "express"
17
+ ],
18
+ "license": "MIT",
19
+ "bugs": {
20
+ "url": "https://github.com/marklai1998/express-response-middleware/issues"
21
+ },
22
+ "homepage": "https://github.com/marklai1998/express-response-middleware#readme",
23
+ "devDependencies": {
24
+ "@types/node": "22.9.1",
25
+ "bluebird": "^3.5.1",
26
+ "express": "^4.16.3",
27
+ "mocha": "^5.2.0",
28
+ "prettier": "3.5.2",
29
+ "should": "^13.2.3",
30
+ "supertest": "^3.1.0"
31
+ },
32
+ "dependencies": {},
33
+ "scripts": {
34
+ "test": "mocha",
35
+ "lint:format": "prettier --check index.js index.d.ts package.json",
36
+ "lint:format:fix": "prettier --write index.js index.d.ts package.json"
37
+ }
38
+ }
@@ -0,0 +1,66 @@
1
+ 'use strict'
2
+
3
+ let should = require('should'),
4
+ express = require('express'),
5
+ request = require('supertest'),
6
+ mung = require('../')
7
+
8
+ describe('mung headers', () => {
9
+ it('should return the munged headers', done => {
10
+ function inspect(req, res) {
11
+ res.set('x-inspected-by', 'me')
12
+ }
13
+ let server = express()
14
+ .use(mung.headers(inspect))
15
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
16
+ request(server)
17
+ .get('/')
18
+ .expect(200)
19
+ .expect(res => {
20
+ res.headers.should.have.property('x-inspected-by', 'me')
21
+ res.body.should.eql({ a: 'a' })
22
+ })
23
+ .end(done)
24
+ })
25
+
26
+ it('should work with promises', done => {
27
+ function inspect(req, res) {
28
+ return Promise.resolve(true).then(() => {
29
+ res.set('x-inspected-by', 'me')
30
+ })
31
+ }
32
+ let server = express()
33
+ .use(mung.headersAsync(inspect))
34
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
35
+ request(server)
36
+ .get('/')
37
+ .expect(200)
38
+ .expect(res => {
39
+ res.headers.should.have.property('x-inspected-by', 'me')
40
+ res.body.should.eql({ a: 'a' })
41
+ })
42
+ .end(done)
43
+ })
44
+
45
+ it('should 500 on a synchronous exception', done => {
46
+ function error(req, res) {
47
+ req.hopefully_fails()
48
+ }
49
+ let server = express()
50
+ .use(mung.headers(error))
51
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
52
+ request(server).get('/').expect(500).end(done)
53
+ })
54
+
55
+ it('should 500 on an asynchronous exception', done => {
56
+ function error(req, res) {
57
+ return Promise.resolve(true).then(() => {
58
+ req.hopefully_fails()
59
+ })
60
+ }
61
+ let server = express()
62
+ .use(mung.headersAsync(error))
63
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
64
+ request(server).get('/').expect(500).end(done)
65
+ })
66
+ })
package/test/json.js ADDED
@@ -0,0 +1,192 @@
1
+ 'use strict'
2
+
3
+ let should = require('should'),
4
+ express = require('express'),
5
+ request = require('supertest'),
6
+ mung = require('../')
7
+
8
+ describe('mung json', () => {
9
+ function noop(json, req, res) {}
10
+
11
+ function inspect(json, req, res) {
12
+ json.inspected_by = 'me'
13
+ }
14
+
15
+ function remove(json, req, res) {
16
+ return null
17
+ }
18
+
19
+ function reduce(json, req, res) {
20
+ return json.a
21
+ }
22
+
23
+ function life(json, req, res) {
24
+ return 42
25
+ }
26
+
27
+ function error(json, req, res) {
28
+ json.foo.bar.hopefully.fails()
29
+ }
30
+
31
+ it('should return the munged JSON result', done => {
32
+ let server = express()
33
+ .use(mung.json(inspect))
34
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
35
+ request(server)
36
+ .get('/')
37
+ .expect(200)
38
+ .expect(res => {
39
+ let expected = { a: 'a', inspected_by: 'me' }
40
+ res.body.should.eql(expected)
41
+ res.headers['content-length'].should.equal(
42
+ JSON.stringify(expected).length.toString()
43
+ )
44
+ })
45
+ .end(done)
46
+ })
47
+
48
+ it('should not mung an error response (by default)', done => {
49
+ let server = express()
50
+ .use(mung.json(inspect))
51
+ .get('/', (req, res) => res.status(404).json({ a: 'a' }).end())
52
+ request(server)
53
+ .get('/')
54
+ .expect(404)
55
+ .expect(res => {
56
+ res.body.should.not.have.property('inspected_by')
57
+ })
58
+ .end(done)
59
+ })
60
+
61
+ it('should mung an error response when told to', done => {
62
+ let server = express()
63
+ .use(mung.json(inspect, { runOnError: true }))
64
+ .get('/', (req, res) => res.status(404).json({ a: 'a' }).end())
65
+ request(server)
66
+ .get('/')
67
+ .expect(404)
68
+ .expect(res => {
69
+ let expected = { a: 'a', inspected_by: 'me' }
70
+ res.body.should.eql(expected)
71
+ res.headers['content-length'].should.equal(
72
+ JSON.stringify(expected).length.toString()
73
+ )
74
+ })
75
+ .end(done)
76
+ })
77
+
78
+ it('should return 204 on null JSON result', done => {
79
+ let server = express()
80
+ .use(mung.json(remove))
81
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }))
82
+ request(server).get('/').expect(204).end(done)
83
+ })
84
+
85
+ it('should return the munged JSON result from a res.send', done => {
86
+ let server = express()
87
+ .use(mung.json(inspect))
88
+ .get('/', (req, res) => res.status(200).send({ a: 'a' }).end())
89
+ request(server)
90
+ .get('/')
91
+ .expect(200)
92
+ .expect(res => {
93
+ let expected = { a: 'a', inspected_by: 'me' }
94
+ res.body.should.eql(expected)
95
+ res.headers['content-length'].should.equal(
96
+ JSON.stringify(expected).length.toString()
97
+ )
98
+ })
99
+ .end(done)
100
+ })
101
+
102
+ it('should return a munged scalar result as text/plain', done => {
103
+ let server = express()
104
+ .use(mung.json(reduce))
105
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
106
+ request(server)
107
+ .get('/')
108
+ .expect(200)
109
+ .expect(res => {
110
+ res.text.should.equal('a')
111
+ res.headers.should.have.property(
112
+ 'content-type',
113
+ 'text/plain; charset=utf-8'
114
+ )
115
+ })
116
+ .end(done)
117
+ })
118
+
119
+ it('should return a munged number as text/plain', done => {
120
+ let server = express()
121
+ .use(mung.json(life))
122
+ .get('/', (req, res) => res.status(200).json('the meaning of life').end())
123
+ request(server)
124
+ .get('/')
125
+ .expect(200)
126
+ .expect(res => {
127
+ res.text.should.equal('42')
128
+ res.headers.should.have.property(
129
+ 'content-type',
130
+ 'text/plain; charset=utf-8'
131
+ )
132
+ })
133
+ .end(done)
134
+ })
135
+
136
+ it('should return a number as application/json', done => {
137
+ let server = express()
138
+ .use(mung.json(noop))
139
+ .get('/', (req, res) => res.status(200).json(42).end())
140
+ request(server)
141
+ .get('/')
142
+ .expect(200)
143
+ .expect(res => {
144
+ res.text.should.equal('42')
145
+ res.headers.should.have.property(
146
+ 'content-type',
147
+ 'application/json; charset=utf-8'
148
+ )
149
+ })
150
+ .end(done)
151
+ })
152
+
153
+ it('should abort if a response is sent', done => {
154
+ function error(json, req, res) {
155
+ res.status(403).send('no permissions')
156
+ }
157
+ let server = express()
158
+ .use(mung.json(error))
159
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
160
+ request(server)
161
+ .get('/')
162
+ .expect(403)
163
+ .expect(res => {
164
+ res.text.should.equal('no permissions')
165
+ res.headers.should.have.property(
166
+ 'content-type',
167
+ 'text/html; charset=utf-8'
168
+ )
169
+ })
170
+ .end(done)
171
+ })
172
+
173
+ it('should 500 on a synchronous exception', done => {
174
+ let server = express()
175
+ .use((err, req, res, next) => res.status(500).send(err.message).end())
176
+ .use(mung.json(error))
177
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
178
+ request(server).get('/').expect(500).end(done)
179
+ })
180
+
181
+ it('should 500 on an asynchronous exception', done => {
182
+ let server = express()
183
+ .use((err, req, res, next) => res.status(500).send(err.message).end())
184
+ .use(mung.json(error))
185
+ .get('/', (req, res) => {
186
+ process.nextTick(() => {
187
+ res.status(200).json({ a: 'a' }).end()
188
+ })
189
+ })
190
+ request(server).get('/').expect(500).end(done)
191
+ })
192
+ })
@@ -0,0 +1,170 @@
1
+ 'use strict'
2
+
3
+ let should = require('should'),
4
+ Promise = require('bluebird'),
5
+ express = require('express'),
6
+ request = require('supertest'),
7
+ mung = require('../')
8
+
9
+ describe('mung jsonAsync', () => {
10
+ function noop(json, req, res) {
11
+ return Promise.resolve(json)
12
+ }
13
+
14
+ function inspect(json, req, res) {
15
+ return Promise.resolve(json).then(json => {
16
+ json.inspected_by = 'me'
17
+ return json
18
+ })
19
+ }
20
+
21
+ function remove(json, req, res) {
22
+ return Promise.resolve(json).then(json => null)
23
+ }
24
+
25
+ function reduce(json, req, res) {
26
+ return Promise.resolve(json).then(json => json.a)
27
+ }
28
+
29
+ function life(json, req, res) {
30
+ return Promise.resolve(json).then(json => 42)
31
+ }
32
+
33
+ function error(json, req, res) {
34
+ return Promise.resolve(json).then(json => json.foo.bar.hopefully.fails())
35
+ }
36
+
37
+ it('should return the munged JSON result', done => {
38
+ let server = express()
39
+ .use(mung.jsonAsync(inspect))
40
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
41
+ request(server)
42
+ .get('/')
43
+ .expect(200)
44
+ .expect(res => {
45
+ let expected = { a: 'a', inspected_by: 'me' }
46
+ res.body.should.eql(expected)
47
+ res.headers['content-length'].should.equal(
48
+ JSON.stringify(expected).length.toString()
49
+ )
50
+ })
51
+ .end(done)
52
+ })
53
+
54
+ it('should not mung an error response (by default)', done => {
55
+ let server = express()
56
+ .use(mung.jsonAsync(inspect))
57
+ .get('/', (req, res) => res.status(404).json({ a: 'a' }).end())
58
+ request(server)
59
+ .get('/')
60
+ .expect(404)
61
+ .expect(res => {
62
+ res.body.should.not.have.property('inspected_by')
63
+ })
64
+ .end(done)
65
+ })
66
+
67
+ it('should mung an error response when told to', done => {
68
+ let server = express()
69
+ .use(mung.jsonAsync(inspect, { runOnError: true }))
70
+ .get('/', (req, res) => res.status(404).json({ a: 'a' }).end())
71
+ request(server)
72
+ .get('/')
73
+ .expect(404)
74
+ .expect(res => {
75
+ let expected = { a: 'a', inspected_by: 'me' }
76
+ res.body.should.eql(expected)
77
+ res.headers['content-length'].should.equal(
78
+ JSON.stringify(expected).length.toString()
79
+ )
80
+ })
81
+ .end(done)
82
+ })
83
+
84
+ it('should return 204 on null JSON result', done => {
85
+ let server = express()
86
+ .use(mung.jsonAsync(remove))
87
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
88
+ request(server).get('/').expect(204).end(done)
89
+ })
90
+
91
+ it('should return a munged scalar result as text/plain', done => {
92
+ let server = express()
93
+ .use(mung.jsonAsync(reduce))
94
+ .get('/', (req, res) => res.status(200).json({ a: 'alpha' }).end())
95
+ request(server)
96
+ .get('/')
97
+ .expect(200)
98
+ .expect(res => {
99
+ res.text.should.equal('alpha')
100
+ res.headers.should.have.property(
101
+ 'content-type',
102
+ 'text/plain; charset=utf-8'
103
+ )
104
+ })
105
+ .end(done)
106
+ })
107
+
108
+ it('should return a munged number as text/plain', done => {
109
+ let server = express()
110
+ .use(mung.jsonAsync(life))
111
+ .get('/', (req, res) => res.status(200).json('the meaning of life').end())
112
+ request(server)
113
+ .get('/')
114
+ .expect(200)
115
+ .expect(res => {
116
+ res.text.should.equal('42')
117
+ res.headers.should.have.property(
118
+ 'content-type',
119
+ 'text/plain; charset=utf-8'
120
+ )
121
+ })
122
+ .end(done)
123
+ })
124
+
125
+ it('should return a number as application/json', done => {
126
+ let server = express()
127
+ .use(mung.jsonAsync(noop))
128
+ .get('/', (req, res) => res.status(200).json(42).end())
129
+ request(server)
130
+ .get('/')
131
+ .expect(200)
132
+ .expect(res => {
133
+ res.text.should.equal('42')
134
+ res.headers.should.have.property(
135
+ 'content-type',
136
+ 'application/json; charset=utf-8'
137
+ )
138
+ })
139
+ .end(done)
140
+ })
141
+
142
+ it('should abort if a response is sent', done => {
143
+ function error(json, req, res) {
144
+ res.status(403).send('no permissions')
145
+ return Promise.resolve(json)
146
+ }
147
+ let server = express()
148
+ .use(mung.jsonAsync(error))
149
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
150
+ request(server)
151
+ .get('/')
152
+ .expect(403)
153
+ .expect(res => {
154
+ res.text.should.equal('no permissions')
155
+ res.headers.should.have.property(
156
+ 'content-type',
157
+ 'text/html; charset=utf-8'
158
+ )
159
+ })
160
+ .end(done)
161
+ })
162
+
163
+ it('should 500 on an exception', done => {
164
+ let server = express()
165
+ .use((err, req, res, next) => res.status(501).send(err.message).end())
166
+ .use(mung.jsonAsync(error))
167
+ .get('/', (req, res) => res.status(200).json({ a: 'a' }).end())
168
+ request(server).get('/').expect(500).end(done)
169
+ })
170
+ })
package/test/write.js ADDED
@@ -0,0 +1,160 @@
1
+ 'use strict'
2
+
3
+ let should = require('should'),
4
+ express = require('express'),
5
+ request = require('supertest'),
6
+ mung = require('../')
7
+
8
+ describe('mung write', () => {
9
+ let originalResponseTextBody
10
+ let originalResponseJSONBody
11
+ let modifiedResponseTextBody
12
+
13
+ beforeEach(() => {
14
+ originalResponseTextBody = 'This is the response body'
15
+ modifiedResponseTextBody = 'This is the response body with more content'
16
+ originalResponseJSONBody = {
17
+ a: 'a',
18
+ }
19
+ })
20
+
21
+ function appendText(chunk, encoding, req, res) {
22
+ return chunk + ' with more content'
23
+ }
24
+
25
+ function inspectJson(chunk, encoding, req, res) {
26
+ try {
27
+ const json = JSON.parse(chunk)
28
+ json.inspected_by = 'me'
29
+ return JSON.stringify(json)
30
+ } catch (e) {
31
+ console.log('JSON parse error')
32
+ throw e
33
+ }
34
+ }
35
+
36
+ function remove(chunk, encoding, req, res) {
37
+ return null
38
+ }
39
+
40
+ function error(chunk, encoding, req, res) {
41
+ chunk.foo.bar.hopefully.fails()
42
+ }
43
+
44
+ function error403(chunk, encoding, req, res) {
45
+ res.status(403).json({ foo: 'bar ' })
46
+ }
47
+
48
+ it('should return the munged text result', done => {
49
+ const server = express()
50
+ .use(mung.write(appendText))
51
+ .get('/', (req, res) => {
52
+ res.status(200).write(originalResponseTextBody)
53
+ res.end()
54
+ })
55
+ request(server)
56
+ .get('/')
57
+ .expect(200)
58
+ .expect(res => {
59
+ res.text.should.eql(modifiedResponseTextBody)
60
+ })
61
+ .end(done)
62
+ })
63
+
64
+ it('should return a munged `body` when the content type is application/json', done => {
65
+ const server = express()
66
+ .use(mung.write(inspectJson))
67
+ .get('/', (req, res) => {
68
+ res
69
+ .set('Content-Type', 'application/json')
70
+ .status(200)
71
+ .write(JSON.stringify(originalResponseJSONBody))
72
+ res.end()
73
+ })
74
+ request(server)
75
+ .get('/')
76
+ .expect(200)
77
+ .expect(res => {
78
+ const expectedJSON = { a: 'a', inspected_by: 'me' }
79
+ const expectedStringified = JSON.stringify(expectedJSON)
80
+ res.body.should.eql(expectedJSON)
81
+ })
82
+ .end(done)
83
+ })
84
+
85
+ it('should not mung an error response (by default)', done => {
86
+ const server = express()
87
+ .use(mung.write(appendText))
88
+ .get('/', (req, res) => {
89
+ res.status(404).write(originalResponseTextBody)
90
+ res.end()
91
+ })
92
+ request(server)
93
+ .get('/')
94
+ .expect(404)
95
+ .expect(res => {
96
+ res.text.should.equal(originalResponseTextBody)
97
+ res.body.should.deepEqual({})
98
+ })
99
+ .end(done)
100
+ })
101
+
102
+ it('should mung an error response when told to', done => {
103
+ const server = express()
104
+ .use(mung.write(appendText, { runOnError: true }))
105
+ .get('/', (req, res) => {
106
+ res.status(404).write(originalResponseTextBody)
107
+ res.end()
108
+ })
109
+ request(server)
110
+ .get('/')
111
+ .expect(404)
112
+ .expect(res => {
113
+ res.text.should.eql(modifiedResponseTextBody)
114
+ })
115
+ .end(done)
116
+ })
117
+
118
+ it('should abort if a response is sent', done => {
119
+ const server = express()
120
+ .use(mung.write(error403))
121
+ .get('/', (req, res) => {
122
+ res
123
+ .set('Content-Type', 'application/json')
124
+ .status(200)
125
+ .write(originalResponseTextBody)
126
+ res.end()
127
+ })
128
+ request(server).get('/').expect(403).end(done)
129
+ })
130
+
131
+ it('should 500 on a synchronous exception', done => {
132
+ const server = express()
133
+ .use((err, req, res, next) => res.status(500).send(err.message).end())
134
+ .use(mung.write(error))
135
+ .get('/', (req, res) => {
136
+ res
137
+ .set('Content-Type', 'application/json')
138
+ .status(200)
139
+ .write(originalResponseTextBody)
140
+ res.end()
141
+ })
142
+ request(server).get('/').expect(500).end(done)
143
+ })
144
+
145
+ it('should 500 on an asynchronous exception', done => {
146
+ const server = express()
147
+ .use((err, req, res, next) => res.status(500).send(err.message).end())
148
+ .use(mung.write(error))
149
+ .get('/', (req, res) => {
150
+ process.nextTick(() => {
151
+ res
152
+ .set('Content-Type', 'application/json')
153
+ .status(200)
154
+ .write(originalResponseTextBody)
155
+ res.end()
156
+ })
157
+ })
158
+ request(server).get('/').expect(500).end(done)
159
+ })
160
+ })