express-response-middleware 1.0.0 → 2.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,70 @@
1
+ import { Request, RequestHandler, Response } from 'express'
2
+ import { errorHandler } from './utils/errorHandler'
3
+
4
+ export type TransformChunk = (
5
+ chunk: string | Buffer,
6
+ encoding: string | null,
7
+ request: Request,
8
+ response: Response
9
+ ) => void | string | Buffer | Promise<void> | Promise<string> | Promise<Buffer>
10
+
11
+ export const writeMiddleware =
12
+ (fn: TransformChunk): RequestHandler =>
13
+ (req, res, next) => {
14
+ const originalWrite = res.write
15
+ const originalEndFn = res.end
16
+
17
+ res.write = function (this: Response, chunk) {
18
+ if (res.writableEnded) return false
19
+
20
+ let mayBePromise
21
+ try {
22
+ mayBePromise = fn(
23
+ chunk,
24
+ // Since `encoding` is an optional argument to `res.write`,
25
+ // make sure it is a string and not actually the callback.
26
+ typeof arguments[1] === 'string' ? arguments[1] : null,
27
+ req,
28
+ res
29
+ )
30
+ } catch (e) {
31
+ errorHandler(e, req, res, next)
32
+ return false
33
+ }
34
+
35
+ if (mayBePromise instanceof Promise) {
36
+ mayBePromise.then(result => {
37
+ try {
38
+ res.end = originalEndFn
39
+
40
+ if (res.writableEnded) return false
41
+
42
+ arguments[0] = result === undefined ? chunk : result
43
+
44
+ const writeResponse = originalWrite.apply(res, arguments as any)
45
+
46
+ if (res.__isEnd) res.end()
47
+
48
+ return writeResponse
49
+ } catch (e) {
50
+ errorHandler(e, req, res, next)
51
+ return false
52
+ }
53
+ })
54
+
55
+ res.end = function (this: Response) {
56
+ this.__isEnd = true
57
+ return res
58
+ }
59
+ return false
60
+ } else {
61
+ const result = mayBePromise
62
+ if (res.writableEnded) return false
63
+
64
+ arguments[0] = result === undefined ? chunk : result
65
+ return originalWrite.apply(res, arguments as any)
66
+ }
67
+ }
68
+
69
+ next()
70
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "compilerOptions": {
3
+ "types": ["vitest/globals", "node"],
4
+
5
+ "target": "ESNext",
6
+ "lib": ["ESNext"],
7
+ "module": "NodeNext",
8
+ "moduleResolution": "nodenext",
9
+
10
+ "allowJs": false,
11
+ "skipLibCheck": true,
12
+ "esModuleInterop": false,
13
+ "resolveJsonModule": true,
14
+ "isolatedModules": true,
15
+ "noEmit": true,
16
+
17
+ "strict": true,
18
+ "allowSyntheticDefaultImports": true,
19
+ "forceConsistentCasingInFileNames": true,
20
+ "allowUnreachableCode": false,
21
+ "allowUnusedLabels": false,
22
+ "noImplicitOverride": true,
23
+ "noImplicitReturns": true,
24
+ "noUnusedLocals": true,
25
+ "noUnusedParameters": true,
26
+ },
27
+ "include": ["src"]
28
+ }
@@ -0,0 +1,14 @@
1
+ import { defineConfig } from 'vitest/config'
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true,
6
+ environment: 'node',
7
+ coverage: {
8
+ provider: 'v8',
9
+ reporter: ['lcov', 'text'],
10
+ include: ['src'],
11
+ exclude: ['**/tests/**', '**/*.d.ts'],
12
+ },
13
+ },
14
+ })
package/index.js DELETED
@@ -1,203 +0,0 @@
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/test/headers.js DELETED
@@ -1,66 +0,0 @@
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 DELETED
@@ -1,192 +0,0 @@
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
- })