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,194 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+
3
+ const errorHandler = (err, _req, res, _next) => {
4
+ res.status(500).set("content-language", "en").json({ message: err.message }).end();
5
+ return res;
6
+ };
7
+
8
+ const isInSend$1 = new AsyncLocalStorage();
9
+
10
+ const jsonMiddleware = (fn) => (req, res, next) => {
11
+ const originalJsonFn = res.json;
12
+ const originalSendFn = res.send;
13
+ res.send = function() {
14
+ return isInSend$1.run(
15
+ true,
16
+ () => originalSendFn.apply(this, arguments)
17
+ );
18
+ };
19
+ res.json = function(json) {
20
+ const originalEndFn = res.end;
21
+ if (res.headersSent) return res;
22
+ let mayBePromise;
23
+ try {
24
+ mayBePromise = fn(json, req, res);
25
+ } catch (e) {
26
+ res.json = originalJsonFn;
27
+ errorHandler(e, req, res);
28
+ return res;
29
+ }
30
+ if (mayBePromise instanceof Promise) {
31
+ mayBePromise.then((result) => {
32
+ if (res.headersSent) return;
33
+ res.end = originalEndFn;
34
+ originalJsonFn.call(this, result === void 0 ? json : result);
35
+ }).catch((e) => {
36
+ res.json = originalJsonFn;
37
+ res.end = originalEndFn;
38
+ errorHandler(e, req, res);
39
+ });
40
+ res.end = function() {
41
+ if (isInSend$1.getStore()) {
42
+ originalEndFn.apply(this, arguments);
43
+ }
44
+ return res;
45
+ };
46
+ } else {
47
+ const result = mayBePromise;
48
+ if (res.headersSent) return res;
49
+ originalJsonFn.call(this, result === void 0 ? json : result);
50
+ }
51
+ return res;
52
+ };
53
+ next();
54
+ };
55
+
56
+ const endMiddleware = (fn) => (req, res, next) => {
57
+ const originalEndFn = res.end;
58
+ res.end = function() {
59
+ if (res.headersSent) return originalEndFn.apply(this, arguments);
60
+ let mayBePromise;
61
+ try {
62
+ mayBePromise = fn(req, res);
63
+ } catch (e) {
64
+ res.end = originalEndFn;
65
+ errorHandler(e, req, res);
66
+ return res;
67
+ }
68
+ if (mayBePromise instanceof Promise) {
69
+ mayBePromise.then(() => {
70
+ if (res.headersSent) {
71
+ console.error(
72
+ "sending response while in endMiddleware is undefined behaviour"
73
+ );
74
+ return;
75
+ }
76
+ originalEndFn.apply(this, arguments);
77
+ }).catch((e) => {
78
+ res.end = originalEndFn;
79
+ errorHandler(e, req, res);
80
+ });
81
+ res.end = function() {
82
+ return res;
83
+ };
84
+ } else {
85
+ if (res.headersSent) {
86
+ console.error(
87
+ "sending response while in endMiddleware is undefined behaviour"
88
+ );
89
+ return res;
90
+ }
91
+ return originalEndFn.apply(this, arguments);
92
+ }
93
+ return res;
94
+ };
95
+ next();
96
+ };
97
+
98
+ const writeMiddleware = (fn) => (req, res, next) => {
99
+ const originalWrite = res.write;
100
+ const originalEndFn = res.end;
101
+ res.write = function(chunk) {
102
+ if (res.writableEnded) return false;
103
+ let mayBePromise;
104
+ try {
105
+ mayBePromise = fn(
106
+ chunk,
107
+ // Since `encoding` is an optional argument to `res.write`,
108
+ // make sure it is a string and not actually the callback.
109
+ typeof arguments[1] === "string" ? arguments[1] : null,
110
+ req,
111
+ res
112
+ );
113
+ } catch (e) {
114
+ errorHandler(e, req, res);
115
+ return false;
116
+ }
117
+ if (mayBePromise instanceof Promise) {
118
+ mayBePromise.then((result) => {
119
+ try {
120
+ res.end = originalEndFn;
121
+ if (res.writableEnded) return false;
122
+ arguments[0] = result === void 0 ? chunk : result;
123
+ const writeResponse = originalWrite.apply(res, arguments);
124
+ if (res.__isEnd) res.end();
125
+ return writeResponse;
126
+ } catch (e) {
127
+ errorHandler(e, req, res);
128
+ return false;
129
+ }
130
+ });
131
+ res.end = function() {
132
+ this.__isEnd = true;
133
+ return res;
134
+ };
135
+ return false;
136
+ } else {
137
+ const result = mayBePromise;
138
+ if (res.writableEnded) return false;
139
+ arguments[0] = result === void 0 ? chunk : result;
140
+ return originalWrite.apply(res, arguments);
141
+ }
142
+ };
143
+ next();
144
+ };
145
+
146
+ const isInSend = new AsyncLocalStorage();
147
+ const jsonpMiddleware = (fn) => (req, res, next) => {
148
+ const originalJsonpFn = res.jsonp;
149
+ const originalSendFn = res.send;
150
+ res.send = function() {
151
+ return isInSend.run(
152
+ true,
153
+ () => originalSendFn.apply(this, arguments)
154
+ );
155
+ };
156
+ res.jsonp = function(json) {
157
+ const originalEndFn = res.end;
158
+ if (res.headersSent) return res;
159
+ let mayBePromise;
160
+ try {
161
+ mayBePromise = fn(json, req, res);
162
+ } catch (e) {
163
+ res.json = originalJsonpFn;
164
+ errorHandler(e, req, res);
165
+ return res;
166
+ }
167
+ if (mayBePromise instanceof Promise) {
168
+ mayBePromise.then((result) => {
169
+ if (res.headersSent) return;
170
+ res.end = originalEndFn;
171
+ originalJsonpFn.call(this, result === void 0 ? json : result);
172
+ }).catch((e) => {
173
+ res.jsonp = originalJsonpFn;
174
+ res.end = originalEndFn;
175
+ errorHandler(e, req, res);
176
+ });
177
+ res.end = function() {
178
+ if (isInSend.getStore()) {
179
+ originalEndFn.apply(this, arguments);
180
+ }
181
+ return res;
182
+ };
183
+ } else {
184
+ const result = mayBePromise;
185
+ if (res.headersSent) return res;
186
+ originalJsonpFn.call(this, result === void 0 ? json : result);
187
+ }
188
+ return res;
189
+ };
190
+ next();
191
+ };
192
+
193
+ export { endMiddleware, jsonMiddleware, jsonpMiddleware, writeMiddleware };
194
+ //# sourceMappingURL=main.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.mjs","sources":["../../src/utils/errorHandler.ts","../../src/utils/asyncLocalStorage.ts","../../src/jsonMiddleware.ts","../../src/endMiddleware.ts","../../src/writeMiddleware.ts","../../src/jsonpMiddleware.ts"],"sourcesContent":["import { ErrorRequestHandler } from 'express'\n\nexport const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {\n res\n .status(500)\n .set('content-language', 'en')\n .json({ message: err.message })\n .end()\n return res\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nexport const isInSend = new AsyncLocalStorage<boolean>()\n","import { Request, RequestHandler, Response } from 'express'\nimport { errorHandler } from './utils/errorHandler'\nimport { isInSend } from './utils/asyncLocalStorage'\n\nexport type TransformJson<T = {}> = (\n body: T,\n request: Request,\n response: Response\n) => unknown | Promise<unknown>\n\nexport const jsonMiddleware =\n (fn: TransformJson): RequestHandler =>\n (req, res, next) => {\n const originalJsonFn = res.json\n const originalSendFn = res.send\n\n res.send = function (this: Response) {\n return isInSend.run(true, () =>\n originalSendFn.apply(this, arguments as any)\n )\n }\n\n res.json = function (this: Response, json) {\n const originalEndFn = res.end\n\n if (res.headersSent) return res\n\n let mayBePromise\n try {\n mayBePromise = fn(json, req, res)\n } catch (e) {\n res.json = originalJsonFn\n errorHandler(e, req, res, next)\n return res\n }\n\n if (mayBePromise instanceof Promise) {\n mayBePromise\n .then(result => {\n if (res.headersSent) return\n res.end = originalEndFn\n\n originalJsonFn.call(this, result === undefined ? json : result)\n })\n .catch(e => {\n res.json = originalJsonFn\n res.end = originalEndFn\n errorHandler(e, req, res, next)\n })\n\n // Prevent end being called wile promise still running\n res.end = function (this: Response) {\n // Res.send will call Res.end, when send is call inside the middleware, do it actually\n if (isInSend.getStore()) {\n originalEndFn.apply(this, arguments as any)\n }\n return res\n }\n } else {\n const result = mayBePromise\n\n if (res.headersSent) return res\n\n originalJsonFn.call(this, result === undefined ? json : result)\n }\n\n return res\n }\n\n next()\n }\n","import { Request, RequestHandler, Response } from 'express'\nimport { errorHandler } from './utils/errorHandler'\n\nexport type TransformEnd = (\n request: Request,\n response: Response\n) => unknown | Promise<unknown>\n\nexport const endMiddleware =\n (fn: TransformEnd): RequestHandler =>\n (req, res, next) => {\n const originalEndFn = res.end\n\n res.end = function (this: Response) {\n if (res.headersSent) return originalEndFn.apply(this, arguments as any)\n\n let mayBePromise\n try {\n mayBePromise = fn(req, res)\n } catch (e) {\n res.end = originalEndFn\n errorHandler(e, req, res, next)\n return res\n }\n\n if (mayBePromise instanceof Promise) {\n mayBePromise\n .then(() => {\n if (res.headersSent) {\n console.error(\n 'sending response while in endMiddleware is undefined behaviour'\n )\n return\n }\n\n originalEndFn.apply(this, arguments as any)\n })\n .catch(e => {\n res.end = originalEndFn\n errorHandler(e, req, res, next)\n })\n\n res.end = function (this: Response) {\n return res\n }\n } else {\n if (res.headersSent) {\n console.error(\n 'sending response while in endMiddleware is undefined behaviour'\n )\n return res\n }\n\n return originalEndFn.apply(this, arguments as any)\n }\n\n return res\n }\n\n next()\n }\n","import { Request, RequestHandler, Response } from 'express'\nimport { errorHandler } from './utils/errorHandler'\n\nexport type TransformChunk = (\n chunk: string | Buffer,\n encoding: string | null,\n request: Request,\n response: Response\n) => void | string | Buffer | Promise<void> | Promise<string> | Promise<Buffer>\n\nexport const writeMiddleware =\n (fn: TransformChunk): RequestHandler =>\n (req, res, next) => {\n const originalWrite = res.write\n const originalEndFn = res.end\n\n res.write = function (this: Response, chunk) {\n if (res.writableEnded) return false\n\n let mayBePromise\n try {\n mayBePromise = fn(\n chunk,\n // Since `encoding` is an optional argument to `res.write`,\n // make sure it is a string and not actually the callback.\n typeof arguments[1] === 'string' ? arguments[1] : null,\n req,\n res\n )\n } catch (e) {\n errorHandler(e, req, res, next)\n return false\n }\n\n if (mayBePromise instanceof Promise) {\n mayBePromise.then(result => {\n try {\n res.end = originalEndFn\n\n if (res.writableEnded) return false\n\n arguments[0] = result === undefined ? chunk : result\n\n const writeResponse = originalWrite.apply(res, arguments as any)\n\n if (res.__isEnd) res.end()\n\n return writeResponse\n } catch (e) {\n errorHandler(e, req, res, next)\n return false\n }\n })\n\n res.end = function (this: Response) {\n this.__isEnd = true\n return res\n }\n return false\n } else {\n const result = mayBePromise\n if (res.writableEnded) return false\n\n arguments[0] = result === undefined ? chunk : result\n return originalWrite.apply(res, arguments as any)\n }\n }\n\n next()\n }\n","import { Request, RequestHandler, Response } from 'express'\nimport { errorHandler } from './utils/errorHandler'\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\nexport type TransformJsonp<T = {}> = (\n body: T,\n request: Request,\n response: Response\n) => unknown | Promise<unknown>\n\nconst isInSend = new AsyncLocalStorage<boolean>()\n\nexport const jsonpMiddleware =\n (fn: TransformJsonp): RequestHandler =>\n (req, res, next) => {\n const originalJsonpFn = res.jsonp\n const originalSendFn = res.send\n\n res.send = function (this: Response) {\n return isInSend.run(true, () =>\n originalSendFn.apply(this, arguments as any)\n )\n }\n\n res.jsonp = function (this: Response, json) {\n const originalEndFn = res.end\n\n if (res.headersSent) return res\n\n let mayBePromise\n try {\n mayBePromise = fn(json, req, res)\n } catch (e) {\n res.json = originalJsonpFn\n errorHandler(e, req, res, next)\n return res\n }\n\n if (mayBePromise instanceof Promise) {\n mayBePromise\n .then(result => {\n if (res.headersSent) return\n res.end = originalEndFn\n\n originalJsonpFn.call(this, result === undefined ? json : result)\n })\n .catch(e => {\n res.jsonp = originalJsonpFn\n res.end = originalEndFn\n errorHandler(e, req, res, next)\n })\n\n // Prevent end being called wile promise still running\n res.end = function (this: Response) {\n // Res.send will call Res.end, when send is call inside the middleware, do it actually\n if (isInSend.getStore()) {\n originalEndFn.apply(this, arguments as any)\n }\n return res\n }\n } else {\n const result = mayBePromise\n\n if (res.headersSent) return res\n\n originalJsonpFn.call(this, result === undefined ? json : result)\n }\n\n return res\n }\n\n next()\n }\n"],"names":["isInSend"],"mappings":";;AAEO,MAAM,YAAoC,GAAA,CAAC,GAAK,EAAA,IAAA,EAAM,KAAK,KAAU,KAAA;AAC1E,EAAA,GAAA,CACG,MAAO,CAAA,GAAG,CACV,CAAA,GAAA,CAAI,oBAAoB,IAAI,CAAA,CAC5B,IAAK,CAAA,EAAE,OAAS,EAAA,GAAA,CAAI,OAAQ,EAAC,EAC7B,GAAI,EAAA;AACP,EAAO,OAAA,GAAA;AACT,CAAA;;ACPa,MAAAA,UAAA,GAAW,IAAI,iBAA2B,EAAA;;ACQhD,MAAM,iBACX,CAAC,EAAA,KACD,CAAC,GAAA,EAAK,KAAK,IAAS,K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AM,CAAA;AAAA;AAGjE,IAAO,OAAA,GAAA;AAAA,GACT;AAEA,EAAK,IAAA,EAAA;AACP;;;;"}
@@ -0,0 +1,153 @@
1
+ # Migrate from `express-mung`
2
+
3
+ - [To V2 (Recommended)](#to-v2)
4
+ - [To V1](#to-v1)
5
+
6
+ ## To V2
7
+
8
+ ### Requirement
9
+
10
+ V2 completely rewrote in ESM with modern syntax
11
+
12
+ - Node 18 or above
13
+
14
+ ### Update Import
15
+
16
+ - `mung.json` => `jsonMiddleware`
17
+ - `mung.jsonAsync` => `jsonMiddleware`
18
+ - `mung.headers` => `endMiddleware`
19
+ - `mung.headersAsync` => `endMiddleware`
20
+
21
+ Before
22
+ ```ts
23
+ import mung from 'express-mung'
24
+
25
+ const myMiddleware = mung.json((json) => {
26
+ // your code
27
+ })
28
+ ```
29
+
30
+ After
31
+ ```ts
32
+ import { jsonMiddleware } from 'express-response-middleware'
33
+
34
+ const myMiddleware = jsonMiddleware((json) => {
35
+ // your code
36
+ })
37
+ ```
38
+
39
+ ### Remove `onError` override
40
+
41
+ It is now impossible to override `onError` due to ESM code base, you should try catch your own error
42
+
43
+ Before
44
+ ```ts
45
+ import mung from 'express-mung'
46
+
47
+ mung.onError = customErrorHandle
48
+
49
+ const myMiddleware = responseMiddleware.json((json) => {
50
+ // your code
51
+ })
52
+ ```
53
+
54
+ After
55
+ ```ts
56
+ import responseMiddleware from 'express-response-middleware'
57
+
58
+ const myMiddleware = responseMiddleware.json((json) => {
59
+ try {
60
+ // your code
61
+ } catch (e){ // onError equivalent
62
+ customErrorHandle(e)
63
+ }
64
+ })
65
+ ```
66
+
67
+ ### Remove `mungError`
68
+
69
+ `mungError` is Removed and callback is always called
70
+
71
+ Before
72
+ ```ts
73
+ import mung from 'express-mung'
74
+
75
+ // Would not run on res.statusCode >= 400, unless mungError is set to true
76
+ const myMiddleware = mung.json((json) => {
77
+ // code
78
+ return json
79
+ })
80
+ ```
81
+
82
+ After
83
+ ```ts
84
+ import responseMiddleware from 'express-response-middleware'
85
+
86
+ // Would always run, you have to do your own filtering
87
+ const myMiddleware = responseMiddleware.json((json) => {
88
+ if (res.statusCode >= 400) return
89
+ return json
90
+ })
91
+ ```
92
+
93
+ ### headerSent Handling
94
+
95
+ Middleware will still call if headers are being sent (res.headersSent === `true`)
96
+
97
+ #### Remove `content-type` and 204 handler
98
+
99
+ - Removed auto `content-type` to `text/plain`, you should set correct content type when returning different data
100
+ - Removed 204 handler with null return, you should set correct status when returning different data
101
+
102
+ > Note. Express allow sending plain text and null with `.json` and content type will still be json + 200, this change is to stick to vanilla behavior
103
+
104
+ Before
105
+ ```ts
106
+ import mung from 'express-mung'
107
+
108
+ const myMiddleware = mung.json((json) => {
109
+ const hasPermission = false
110
+ const shouldSendNull = false
111
+ if (!hasPermission) return "Forbidden" // `content-type` will automatically set to `text/plain`
112
+ if (shouldSendNull) return null // `status` will automatically set to 204
113
+ return json
114
+ })
115
+ ```
116
+
117
+ After
118
+ ```ts
119
+ import responseMiddleware from 'express-response-middleware'
120
+
121
+ const myMiddleware = responseMiddleware.json((json) => {
122
+ const hasPermission = false
123
+ const shouldSendNull = false
124
+ if (!hasPermission) {
125
+ res.send("Forbidden")
126
+ return
127
+ }
128
+ if (shouldSendNull) {
129
+ res.status(204)
130
+ return null
131
+ }
132
+ return json
133
+ })
134
+ ```
135
+
136
+ ## To V1
137
+
138
+ V1 is mostly just fork of `express-mung` with integrated types
139
+
140
+ - Update the import
141
+ - Rename option `mungError` to `runOnError`
142
+
143
+ ```diff
144
+ - import mung from 'express-mung'
145
+ + import responseMiddleware from 'express-response-middleware'
146
+
147
+ const myMiddleware = responseMiddleware.json(() => {
148
+ // code here
149
+ },
150
+ - { mungError: true }
151
+ + { runOnError: true }
152
+ )
153
+ ```
@@ -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/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
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",
3
+ "version": "2.0.0",
4
+ "description": "Transform an express response",
5
+ "main": "dist/cjs/index.cjs",
6
+ "module": "dist/esm/index.mjs",
7
+ "types": "dist/esm/index.d.ts",
7
8
  "repository": {
8
9
  "type": "git",
9
10
  "url": "git+https://github.com/marklai1998/express-response-middleware"
@@ -21,18 +22,29 @@
21
22
  },
22
23
  "homepage": "https://github.com/marklai1998/express-response-middleware#readme",
23
24
  "devDependencies": {
25
+ "@types/express": "4.17.21",
24
26
  "@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"
27
+ "@types/supertest": "6.0.2",
28
+ "@vitest/coverage-v8": "3.0.7",
29
+ "prettier": "3.5.3",
30
+ "rollup": "4.27.3",
31
+ "rollup-plugin-dts": "6.1.1",
32
+ "rollup-plugin-esbuild": "6.2.1",
33
+ "rollup-plugin-peer-deps-external": "2.2.4",
34
+ "supertest": "7.0.0",
35
+ "typescript": "5.8.2",
36
+ "vitest": "3.0.7"
37
+ },
38
+ "peerDependencies": {
39
+ "express": "^4.0.0 || ^5.0.0"
40
+ },
41
+ "engines": {
42
+ "node": ">=18"
31
43
  },
32
- "dependencies": {},
33
44
  "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"
45
+ "build": "rollup -c",
46
+ "test": "vitest run --coverage",
47
+ "lint:format": "prettier --check src package.json",
48
+ "lint:format:fix": "prettier --write src package.json"
37
49
  }
38
50
  }
@@ -0,0 +1,49 @@
1
+ import dts from 'rollup-plugin-dts'
2
+ import peerDepsExternal from 'rollup-plugin-peer-deps-external'
3
+ import esbuild from 'rollup-plugin-esbuild'
4
+
5
+ export default [
6
+ {
7
+ input: 'src/main.ts',
8
+ plugins: [peerDepsExternal(), esbuild()],
9
+ output: [
10
+ {
11
+ dir: 'dist/esm',
12
+ format: 'es',
13
+ sourcemap: true,
14
+ entryFileNames: '[name].mjs',
15
+ chunkFileNames: '[name]-[hash].mjs',
16
+ },
17
+ {
18
+ dir: 'dist/cjs',
19
+ format: 'cjs',
20
+ interop: 'auto',
21
+ sourcemap: true,
22
+ entryFileNames: '[name].cjs',
23
+ chunkFileNames: '[name]-[hash].cjs',
24
+ },
25
+ ],
26
+ },
27
+ {
28
+ input: 'src/main.ts',
29
+ plugins: [
30
+ dts({
31
+ compilerOptions: {
32
+ // https://github.com/Swatinem/rollup-plugin-dts/issues/143
33
+ preserveSymlinks: false,
34
+ },
35
+ }),
36
+ ],
37
+ output: [
38
+ {
39
+ dir: 'dist/esm',
40
+ format: 'es',
41
+ },
42
+ {
43
+ dir: 'dist/cjs',
44
+ format: 'cjs',
45
+ interop: 'auto',
46
+ },
47
+ ],
48
+ },
49
+ ]
@@ -0,0 +1,61 @@
1
+ import { Request, RequestHandler, Response } from 'express'
2
+ import { errorHandler } from './utils/errorHandler'
3
+
4
+ export type TransformEnd = (
5
+ request: Request,
6
+ response: Response
7
+ ) => unknown | Promise<unknown>
8
+
9
+ export const endMiddleware =
10
+ (fn: TransformEnd): RequestHandler =>
11
+ (req, res, next) => {
12
+ const originalEndFn = res.end
13
+
14
+ res.end = function (this: Response) {
15
+ if (res.headersSent) return originalEndFn.apply(this, arguments as any)
16
+
17
+ let mayBePromise
18
+ try {
19
+ mayBePromise = fn(req, res)
20
+ } catch (e) {
21
+ res.end = originalEndFn
22
+ errorHandler(e, req, res, next)
23
+ return res
24
+ }
25
+
26
+ if (mayBePromise instanceof Promise) {
27
+ mayBePromise
28
+ .then(() => {
29
+ if (res.headersSent) {
30
+ console.error(
31
+ 'sending response while in endMiddleware is undefined behaviour'
32
+ )
33
+ return
34
+ }
35
+
36
+ originalEndFn.apply(this, arguments as any)
37
+ })
38
+ .catch(e => {
39
+ res.end = originalEndFn
40
+ errorHandler(e, req, res, next)
41
+ })
42
+
43
+ res.end = function (this: Response) {
44
+ return res
45
+ }
46
+ } else {
47
+ if (res.headersSent) {
48
+ console.error(
49
+ 'sending response while in endMiddleware is undefined behaviour'
50
+ )
51
+ return res
52
+ }
53
+
54
+ return originalEndFn.apply(this, arguments as any)
55
+ }
56
+
57
+ return res
58
+ }
59
+
60
+ next()
61
+ }