express-response-middleware 2.1.2 → 2.2.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.
Files changed (41) hide show
  1. package/LICENSE +1 -1
  2. package/dist/{cjs/index.d.cts → index.d.mts} +20 -16
  3. package/dist/{esm/index.d.ts → index.d.ts} +20 -16
  4. package/dist/index.js +207 -0
  5. package/dist/index.mjs +180 -0
  6. package/package.json +25 -28
  7. package/.commitlintrc.json +0 -3
  8. package/.github/workflows/release.yml +0 -42
  9. package/.github/workflows/runTest.yml +0 -59
  10. package/.husky/commit-msg +0 -1
  11. package/.husky/pre-commit +0 -1
  12. package/.husky/pre-push +0 -1
  13. package/.node-version +0 -1
  14. package/CHANGELOG.md +0 -88
  15. package/biome.json +0 -36
  16. package/dist/cjs/index.cjs +0 -196
  17. package/dist/cjs/index.cjs.map +0 -1
  18. package/dist/esm/index.mjs +0 -191
  19. package/dist/esm/index.mjs.map +0 -1
  20. package/docs/MIGRATE_FROM_MUNG.md +0 -153
  21. package/docs/V1_README.md +0 -115
  22. package/pnpm-workspace.yaml +0 -3
  23. package/renovate.json +0 -9
  24. package/rollup.config.js +0 -52
  25. package/src/endMiddleware.ts +0 -61
  26. package/src/index.ts +0 -12
  27. package/src/jsonMiddleware.ts +0 -71
  28. package/src/jsonpMiddleware.ts +0 -73
  29. package/src/sendMiddleware.ts +0 -50
  30. package/src/tests/endMiddleware.test.ts +0 -101
  31. package/src/tests/jsonMiddleware.test.ts +0 -253
  32. package/src/tests/jsonpMiddleware.test.ts +0 -233
  33. package/src/tests/mixAndMatch.test.ts +0 -261
  34. package/src/tests/sendMiddleware.test.ts +0 -219
  35. package/src/tests/testHelpers/sleep.ts +0 -2
  36. package/src/tests/writeMiddleware.test.ts +0 -267
  37. package/src/utils/asyncLocalStorage.ts +0 -3
  38. package/src/utils/errorHandler.ts +0 -9
  39. package/src/writeMiddleware.ts +0 -76
  40. package/tsconfig.json +0 -28
  41. package/vitest.config.ts +0 -14
@@ -1,153 +0,0 @@
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
- ```
package/docs/V1_README.md DELETED
@@ -1,115 +0,0 @@
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
@@ -1,3 +0,0 @@
1
- onlyBuiltDependencies:
2
- - '@biomejs/biome'
3
- - esbuild
package/renovate.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3
- "extends": [
4
- "config:best-practices",
5
- "config:js-lib",
6
- "config:semverAllMonthly",
7
- ":automergeMinor"
8
- ]
9
- }
package/rollup.config.js DELETED
@@ -1,52 +0,0 @@
1
- import dts from 'rollup-plugin-dts';
2
- import esbuild from 'rollup-plugin-esbuild';
3
- import { nodeExternals } from 'rollup-plugin-node-externals';
4
- import peerDepsExternal from 'rollup-plugin-peer-deps-external';
5
-
6
- export default [
7
- {
8
- input: 'src/index.ts',
9
- plugins: [nodeExternals(), peerDepsExternal(), esbuild()],
10
- output: [
11
- {
12
- dir: 'dist/esm',
13
- format: 'es',
14
- sourcemap: true,
15
- entryFileNames: '[name].mjs',
16
- chunkFileNames: '[name]-[hash].mjs',
17
- },
18
- {
19
- dir: 'dist/cjs',
20
- format: 'cjs',
21
- interop: 'auto',
22
- sourcemap: true,
23
- entryFileNames: '[name].cjs',
24
- chunkFileNames: '[name]-[hash].cjs',
25
- },
26
- ],
27
- },
28
- {
29
- input: 'src/index.ts',
30
- plugins: [
31
- dts({
32
- compilerOptions: {
33
- // https://github.com/Swatinem/rollup-plugin-dts/issues/143
34
- preserveSymlinks: false,
35
- },
36
- }),
37
- ],
38
- output: [
39
- {
40
- dir: 'dist/esm',
41
- format: 'es',
42
- },
43
- {
44
- dir: 'dist/cjs',
45
- format: 'cjs',
46
- interop: 'auto',
47
- entryFileNames: '[name].d.cts',
48
- chunkFileNames: '[name]-[hash].d.cts',
49
- },
50
- ],
51
- },
52
- ];
@@ -1,61 +0,0 @@
1
- import type { Request, RequestHandler, Response } from 'express';
2
- import { errorHandler } from './utils/errorHandler.js';
3
-
4
- export type TransformEnd<T = unknown> = (
5
- request: Request,
6
- response: Response,
7
- ) => T | Promise<T>;
8
-
9
- export const endMiddleware =
10
- <T = unknown>(fn: TransformEnd<T>): 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: T | Promise<T>;
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
- };
package/src/index.ts DELETED
@@ -1,12 +0,0 @@
1
- export * from './jsonMiddleware.js';
2
- export * from './endMiddleware.js';
3
- export * from './writeMiddleware.js';
4
- export * from './jsonpMiddleware.js';
5
-
6
- declare global {
7
- namespace Express {
8
- interface Response {
9
- __isEnd?: boolean;
10
- }
11
- }
12
- }
@@ -1,71 +0,0 @@
1
- import type { Request, RequestHandler, Response } from 'express';
2
- import { isInSend } from './utils/asyncLocalStorage.js';
3
- import { errorHandler } from './utils/errorHandler.js';
4
-
5
- export type TransformJson<T = unknown, R = T> = (
6
- body: T,
7
- request: Request,
8
- response: Response,
9
- ) => R | Promise<R>;
10
-
11
- export const jsonMiddleware =
12
- <T = unknown>(fn: TransformJson<T>): RequestHandler =>
13
- (req, res, next) => {
14
- const originalJsonFn = res.json;
15
- const originalSendFn = res.send;
16
-
17
- res.send = function (this: Response) {
18
- return isInSend.run(true, () =>
19
- originalSendFn.apply(this, arguments as any),
20
- );
21
- };
22
-
23
- res.json = function (this: Response, json) {
24
- const originalEndFn = res.end;
25
-
26
- if (res.headersSent) return res;
27
-
28
- let mayBePromise: T | Promise<T>;
29
- try {
30
- mayBePromise = fn(json, req, res);
31
- } catch (e) {
32
- res.json = originalJsonFn;
33
- errorHandler(e, req, res, next);
34
- return res;
35
- }
36
-
37
- if (mayBePromise instanceof Promise) {
38
- mayBePromise
39
- .then((result) => {
40
- if (res.headersSent) return;
41
- res.end = originalEndFn;
42
-
43
- originalJsonFn.call(this, result === undefined ? json : result);
44
- })
45
- .catch((e) => {
46
- res.json = originalJsonFn;
47
- res.end = originalEndFn;
48
- errorHandler(e, req, res, next);
49
- });
50
-
51
- // Prevent end being called wile promise still running
52
- res.end = function (this: Response) {
53
- // Res.send will call Res.end, when send is call inside the middleware, do it actually
54
- if (isInSend.getStore()) {
55
- originalEndFn.apply(this, arguments as any);
56
- }
57
- return res;
58
- };
59
- } else {
60
- const result = mayBePromise;
61
-
62
- if (res.headersSent) return res;
63
-
64
- originalJsonFn.call(this, result === undefined ? json : result);
65
- }
66
-
67
- return res;
68
- };
69
-
70
- next();
71
- };
@@ -1,73 +0,0 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- import type { Request, RequestHandler, Response } from 'express';
3
- import { errorHandler } from './utils/errorHandler.js';
4
-
5
- export type TransformJsonp<T = unknown, R = T> = (
6
- body: T,
7
- request: Request,
8
- response: Response,
9
- ) => R | Promise<R>;
10
-
11
- const isInSend = new AsyncLocalStorage<boolean>();
12
-
13
- export const jsonpMiddleware =
14
- <T = unknown>(fn: TransformJsonp<T>): RequestHandler =>
15
- (req, res, next) => {
16
- const originalJsonpFn = res.jsonp;
17
- const originalSendFn = res.send;
18
-
19
- res.send = function (this: Response) {
20
- return isInSend.run(true, () =>
21
- originalSendFn.apply(this, arguments as any),
22
- );
23
- };
24
-
25
- res.jsonp = function (this: Response, json) {
26
- const originalEndFn = res.end;
27
-
28
- if (res.headersSent) return res;
29
-
30
- let mayBePromise: T | Promise<T>;
31
- try {
32
- mayBePromise = fn(json, req, res);
33
- } catch (e) {
34
- res.json = originalJsonpFn;
35
- errorHandler(e, req, res, next);
36
- return res;
37
- }
38
-
39
- if (mayBePromise instanceof Promise) {
40
- mayBePromise
41
- .then((result) => {
42
- if (res.headersSent) return;
43
- res.end = originalEndFn;
44
-
45
- originalJsonpFn.call(this, result === undefined ? json : result);
46
- })
47
- .catch((e) => {
48
- res.jsonp = originalJsonpFn;
49
- res.end = originalEndFn;
50
- errorHandler(e, req, res, next);
51
- });
52
-
53
- // Prevent end being called wile promise still running
54
- res.end = function (this: Response) {
55
- // Res.send will call Res.end, when send is call inside the middleware, do it actually
56
- if (isInSend.getStore()) {
57
- originalEndFn.apply(this, arguments as any);
58
- }
59
- return res;
60
- };
61
- } else {
62
- const result = mayBePromise;
63
-
64
- if (res.headersSent) return res;
65
-
66
- originalJsonpFn.call(this, result === undefined ? json : result);
67
- }
68
-
69
- return res;
70
- };
71
-
72
- next();
73
- };
@@ -1,50 +0,0 @@
1
- import type { Request, RequestHandler, Response } from 'express';
2
- import { errorHandler } from './utils/errorHandler.js';
3
-
4
- export type TransformSend<T = unknown> = (
5
- body: T,
6
- request: Request,
7
- response: Response,
8
- ) => unknown | Promise<unknown>;
9
-
10
- export const sendMiddleware =
11
- (fn: TransformSend): RequestHandler =>
12
- (req, res, next) => {
13
- const originalSendFn = res.send;
14
-
15
- res.send = function (this: Response, payload) {
16
- if (res.headersSent) return res;
17
-
18
- let mayBePromise: unknown;
19
- try {
20
- mayBePromise = fn(payload, req, res);
21
- } catch (e) {
22
- res.send = originalSendFn;
23
- errorHandler(e, req, res, next);
24
- return res;
25
- }
26
-
27
- if (mayBePromise instanceof Promise) {
28
- mayBePromise
29
- .then((result) => {
30
- if (res.headersSent) return;
31
-
32
- originalSendFn.call(this, result === undefined ? payload : result);
33
- })
34
- .catch((e) => {
35
- res.send = originalSendFn;
36
- errorHandler(e, req, res, next);
37
- });
38
- } else {
39
- const result = mayBePromise;
40
-
41
- if (res.headersSent) return res;
42
-
43
- originalSendFn.call(this, result === undefined ? payload : result);
44
- }
45
-
46
- return res;
47
- };
48
-
49
- next();
50
- };
@@ -1,101 +0,0 @@
1
- import express from 'express';
2
- import request from 'supertest';
3
- import { expect } from 'vitest';
4
- import { type TransformEnd, endMiddleware } from '../index.js';
5
- import { sleep } from './testHelpers/sleep.js';
6
-
7
- describe('endMiddleware', () => {
8
- const header: TransformEnd = (_req, res) => {
9
- res.set('x-inspected-by', 'me');
10
- };
11
-
12
- const headerAsync: TransformEnd = async (_req, res) => {
13
- await sleep();
14
- res.set('x-inspected-by', 'me');
15
- await sleep();
16
-
17
- return;
18
- };
19
-
20
- const header2: TransformEnd = (_req, res) => {
21
- res.set('x-inspected-by-2', 'him');
22
- };
23
-
24
- const headerAsync2: TransformEnd = async (_req, res) => {
25
- await sleep();
26
- res.set('x-inspected-by-2', 'him');
27
- await sleep();
28
-
29
- return;
30
- };
31
-
32
- const error: TransformEnd = (req) => {
33
- (req as any).hopefully_fails();
34
- };
35
-
36
- const errorAsync: TransformEnd = async (req) => {
37
- await sleep();
38
- (req as any).hopefully_fails();
39
- await sleep();
40
-
41
- return;
42
- };
43
-
44
- it.each([header, headerAsync])(
45
- 'should return the headers',
46
- async (handler) => {
47
- const server = express()
48
- .use(endMiddleware(handler))
49
- .get('/', (_req, res) => {
50
- res.status(200).json({ a: 'a' }).end();
51
- });
52
- const response = await request(server).get('/');
53
-
54
- expect(response.status).toStrictEqual(200);
55
- expect(response.body).toStrictEqual({ a: 'a' });
56
- expect(response.headers).toStrictEqual(
57
- expect.objectContaining({
58
- 'x-inspected-by': 'me',
59
- }),
60
- );
61
- },
62
- );
63
-
64
- it.each([
65
- [header, header2],
66
- [header, headerAsync2],
67
- [headerAsync, header2],
68
- [headerAsync, headerAsync2],
69
- ])('should work with multiple middleware', async (handler, handler2) => {
70
- const server = express()
71
- .use(endMiddleware(handler))
72
- .use(endMiddleware(handler2))
73
- .get('/', (_req, res) => {
74
- res.status(200).json({ a: 'a' }).end();
75
- });
76
- const response = await request(server).get('/');
77
-
78
- expect(response.status).toStrictEqual(200);
79
- expect(response.body).toStrictEqual({ a: 'a' });
80
- expect(response.headers).toStrictEqual(
81
- expect.objectContaining({
82
- 'x-inspected-by': 'me',
83
- 'x-inspected-by-2': 'him',
84
- }),
85
- );
86
- });
87
-
88
- it.each([error, errorAsync])(
89
- 'should 500 on a synchronous exception',
90
- async (handler) => {
91
- const server = express()
92
- .use(endMiddleware(handler))
93
- .get('/', (_req, res) => {
94
- res.status(200).json({ a: 'a' }).end();
95
- });
96
- const response = await request(server).get('/');
97
-
98
- expect(response.status).toStrictEqual(500);
99
- },
100
- );
101
- });