express-response-middleware 2.0.1 → 2.1.2

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.
@@ -1,85 +1,126 @@
1
- import express, { ErrorRequestHandler } from 'express'
2
- import request from 'supertest'
3
- import { TransformChunk, writeMiddleware } from '../index'
4
- import { expect } from 'vitest'
5
- import { sleep } from './testHelpers/sleep'
1
+ import express, { type ErrorRequestHandler } from 'express';
2
+ import request from 'supertest';
3
+ import { expect } from 'vitest';
4
+ import { type TransformChunk, writeMiddleware } from '../index.js';
5
+ import { sleep } from './testHelpers/sleep.js';
6
6
 
7
7
  describe('write', () => {
8
- const appendText: TransformChunk = chunk => {
9
- return chunk + ' with more content'
10
- }
8
+ const appendText: TransformChunk = (chunk) => {
9
+ return `${chunk} with more content`;
10
+ };
11
11
 
12
- const appendTextAsync: TransformChunk = async chunk => {
13
- await sleep()
14
- return chunk + ' with more content'
15
- }
12
+ const appendTextAsync: TransformChunk = async (chunk) => {
13
+ await sleep();
14
+ return `${chunk} with more content`;
15
+ };
16
16
 
17
- const appendText2: TransformChunk = chunk => {
18
- return chunk + ' with more content2'
19
- }
17
+ const doNothing: TransformChunk = () => {};
20
18
 
21
- const appendTextAsync2: TransformChunk = async chunk => {
22
- await sleep()
23
- return chunk + ' with more content2'
24
- }
19
+ const doNothingAsync: TransformChunk = async () => {
20
+ await sleep();
21
+ };
25
22
 
26
- const inspectJson: TransformChunk = chunk => {
23
+ const appendText2: TransformChunk = (chunk) => {
24
+ return `${chunk} with more content2`;
25
+ };
26
+
27
+ const appendTextAsync2: TransformChunk = async (chunk) => {
28
+ await sleep();
29
+ return `${chunk} with more content2`;
30
+ };
31
+
32
+ const inspectJson: TransformChunk = (chunk) => {
27
33
  try {
28
- const json = JSON.parse(String(chunk))
29
- json.inspected_by = 'me'
30
- return JSON.stringify(json)
34
+ const json = JSON.parse(String(chunk));
35
+ json.inspected_by = 'me';
36
+ return JSON.stringify({ ...json, inspected_by: 'me' });
31
37
  } catch (e) {
32
- console.log('JSON parse error')
33
- throw e
38
+ console.log('JSON parse error');
39
+ throw e;
34
40
  }
35
- }
41
+ };
36
42
 
37
- const inspectJsonAsync: TransformChunk = chunk => {
43
+ const inspectJsonAsync: TransformChunk = (chunk) => {
38
44
  try {
39
- sleep()
40
- const json = JSON.parse(String(chunk))
41
- json.inspected_by = 'me'
42
- sleep()
43
- return JSON.stringify(json)
45
+ sleep();
46
+ const json = JSON.parse(String(chunk));
47
+ json.inspected_by = 'me';
48
+ sleep();
49
+ return JSON.stringify({ ...json, inspected_by: 'me' });
44
50
  } catch (e) {
45
- console.log('JSON parse error')
46
- throw e
51
+ console.log('JSON parse error');
52
+ throw e;
47
53
  }
48
- }
54
+ };
49
55
 
50
- const error: TransformChunk = chunk => {
51
- ;(chunk as any).foo.bar.hopefully.fails()
52
- }
56
+ const error: TransformChunk = (chunk) => {
57
+ (chunk as any).foo.bar.hopefully.fails();
58
+ };
53
59
 
54
- const errorAsync: TransformChunk = chunk => {
55
- ;(chunk as any).foo.bar.hopefully.fails()
56
- }
60
+ const errorAsync: TransformChunk = async (chunk) => {
61
+ await sleep();
62
+ (chunk as any).foo.bar.hopefully.fails();
63
+ };
57
64
 
58
65
  const error403: TransformChunk = (_chunk, _encoding, _req, res) => {
59
- res.status(403).json({ foo: 'bar ' })
60
- }
66
+ res.status(403).json({ foo: 'bar ' });
67
+ };
61
68
 
62
69
  const error403Async: TransformChunk = (_chunk, _encoding, _req, res) => {
63
- res.status(403).json({ foo: 'bar ' })
64
- }
70
+ res.status(403).json({ foo: 'bar ' });
71
+ };
65
72
 
66
73
  it.each([appendText, appendTextAsync])(
67
74
  'should return the text result',
68
- async handler => {
75
+ async (handler) => {
69
76
  const server = express()
70
77
  .use(writeMiddleware(handler))
71
78
  .get('/', (_req, res) => {
72
- res.status(200).write('This is the response body')
73
- res.end()
74
- })
75
- const response = await request(server).get('/')
79
+ res.status(200).write('This is the response body', 'utf-8');
80
+ res.end();
81
+ });
82
+ const response = await request(server).get('/');
76
83
 
77
- expect(response.status).toStrictEqual(200)
84
+ expect(response.status).toStrictEqual(200);
78
85
  expect(response.text).toStrictEqual(
79
- 'This is the response body with more content'
80
- )
81
- }
82
- )
86
+ 'This is the response body with more content',
87
+ );
88
+ },
89
+ );
90
+
91
+ it.each([appendText, appendTextAsync])(
92
+ 'should not call if header is already sent',
93
+ async (handler) => {
94
+ const handlerSpy = vi.fn(handler);
95
+
96
+ const server = express()
97
+ .use(writeMiddleware(handlerSpy))
98
+ .get('/', (_req, res) => {
99
+ res.end();
100
+ res.status(200).write('This is the response body');
101
+ });
102
+ const response = await request(server).get('/');
103
+
104
+ expect(handlerSpy).not.toHaveBeenCalled();
105
+ expect(response.status).toStrictEqual(200);
106
+ },
107
+ );
108
+
109
+ it.each([doNothing, doNothingAsync])(
110
+ 'should return the text result if callback return void',
111
+ async (handler) => {
112
+ const server = express()
113
+ .use(writeMiddleware(handler))
114
+ .get('/', (_req, res) => {
115
+ res.status(200).write(Buffer.from('This is the response body'));
116
+ res.end();
117
+ });
118
+ const response = await request(server).get('/');
119
+
120
+ expect(response.status).toStrictEqual(200);
121
+ expect(response.text).toStrictEqual('This is the response body');
122
+ },
123
+ );
83
124
 
84
125
  it.each([
85
126
  [
@@ -109,19 +150,19 @@ describe('write', () => {
109
150
  .use(writeMiddleware(handler))
110
151
  .use(writeMiddleware(handler2))
111
152
  .get('/', (_req, res) => {
112
- res.status(200).write('This is the response body')
113
- res.end()
114
- })
115
- const response = await request(server).get('/')
153
+ res.status(200).write('This is the response body');
154
+ res.end();
155
+ });
156
+ const response = await request(server).get('/');
116
157
 
117
- expect(response.status).toStrictEqual(200)
118
- expect(response.text).toStrictEqual(expectStr)
119
- }
120
- )
158
+ expect(response.status).toStrictEqual(200);
159
+ expect(response.text).toStrictEqual(expectStr);
160
+ },
161
+ );
121
162
 
122
163
  it.each([inspectJson, inspectJsonAsync])(
123
164
  'should return a `body` when the content type is application/json',
124
- async handler => {
165
+ async (handler) => {
125
166
  const server = express()
126
167
  .use(writeMiddleware(handler))
127
168
  .get('/', (_req, res) => {
@@ -131,58 +172,59 @@ describe('write', () => {
131
172
  .write(
132
173
  JSON.stringify({
133
174
  a: 'a',
134
- })
135
- )
136
- res.end()
137
- })
138
- const response = await request(server).get('/')
139
-
140
- expect(response.status).toStrictEqual(200)
141
- expect(response.body).toStrictEqual({ a: 'a', inspected_by: 'me' })
142
- }
143
- )
175
+ }),
176
+ );
177
+ res.end();
178
+ });
179
+ const response = await request(server).get('/');
180
+
181
+ expect(response.status).toStrictEqual(200);
182
+ expect(response.body).toStrictEqual({ a: 'a', inspected_by: 'me' });
183
+ },
184
+ );
144
185
 
145
186
  it.each([appendText, appendTextAsync])(
146
187
  'should call callback an error response',
147
- async handler => {
188
+ async (handler) => {
148
189
  const server = express()
149
190
  .use(writeMiddleware(handler))
150
191
  .get('/', (_req, res) => {
151
- res.status(404).write('This is the response body')
152
- res.end()
153
- })
154
- const response = await request(server).get('/')
192
+ res.status(404).write('This is the response body');
193
+ res.end();
194
+ });
195
+ const response = await request(server).get('/');
155
196
 
156
- expect(response.status).toStrictEqual(404)
197
+ expect(response.status).toStrictEqual(404);
157
198
  expect(response.text).toStrictEqual(
158
- 'This is the response body with more content'
159
- )
160
- }
161
- )
199
+ 'This is the response body with more content',
200
+ );
201
+ },
202
+ );
162
203
 
163
204
  it.each([error403, error403Async])(
164
205
  'should abort if a response is sent',
165
- async handler => {
206
+ async (handler) => {
166
207
  const server = express()
167
208
  .use(writeMiddleware(handler))
168
209
  .get('/', (_req, res) => {
169
210
  res
170
211
  .set('Content-Type', 'application/json')
171
212
  .status(200)
172
- .write('This is the response body')
173
- res.end()
174
- })
175
- const response = await request(server).get('/')
213
+ .write('This is the response body');
214
+ res.end();
215
+ });
216
+ const response = await request(server).get('/');
176
217
 
177
- expect(response.status).to.equal(403)
178
- }
179
- )
218
+ expect(response.status).to.equal(403);
219
+ },
220
+ );
180
221
 
181
222
  it.each([error, errorAsync])(
182
223
  'should 500 on a synchronous exception',
183
- async handler => {
184
- const errorHandler: ErrorRequestHandler = (err, _req, res, _next) =>
185
- res.status(500).send(err.message).end()
224
+ async (handler) => {
225
+ const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
226
+ res.status(500).send(err.message).end();
227
+ };
186
228
  const server = express()
187
229
  .use(errorHandler)
188
230
  .use(writeMiddleware(handler))
@@ -190,20 +232,21 @@ describe('write', () => {
190
232
  res
191
233
  .set('Content-Type', 'application/json')
192
234
  .status(200)
193
- .write('This is the response body')
194
- res.end()
195
- })
196
- const response = await request(server).get('/')
235
+ .write('This is the response body');
236
+ res.end();
237
+ });
238
+ const response = await request(server).get('/');
197
239
 
198
- expect(response.status).toStrictEqual(500)
199
- }
200
- )
240
+ expect(response.status).toStrictEqual(500);
241
+ },
242
+ );
201
243
 
202
244
  it.each([error, errorAsync])(
203
245
  'should 500 on an asynchronous exception',
204
- async handler => {
205
- const errorHandler: ErrorRequestHandler = (err, _req, res, _next) =>
206
- res.status(500).send(err.message).end()
246
+ async (handler) => {
247
+ const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
248
+ res.status(500).send(err.message).end();
249
+ };
207
250
  const server = express()
208
251
  .use(errorHandler)
209
252
  .use(writeMiddleware(handler))
@@ -212,13 +255,13 @@ describe('write', () => {
212
255
  res
213
256
  .set('Content-Type', 'application/json')
214
257
  .status(200)
215
- .write('This is the response body')
216
- res.end()
217
- })
218
- })
219
- const response = await request(server).get('/')
258
+ .write('This is the response body');
259
+ res.end();
260
+ });
261
+ });
262
+ const response = await request(server).get('/');
220
263
 
221
- expect(response.status).toStrictEqual(500)
222
- }
223
- )
224
- })
264
+ expect(response.status).toStrictEqual(500);
265
+ },
266
+ );
267
+ });
@@ -1,3 +1,3 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks'
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
2
 
3
- export const isInSend = new AsyncLocalStorage<boolean>()
3
+ export const isInSend = new AsyncLocalStorage<boolean>();
@@ -1,10 +1,9 @@
1
- import { ErrorRequestHandler } from 'express'
1
+ import type { ErrorRequestHandler } from 'express';
2
2
 
3
3
  export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
4
4
  res
5
5
  .status(500)
6
6
  .set('content-language', 'en')
7
7
  .json({ message: err.message })
8
- .end()
9
- return res
10
- }
8
+ .end();
9
+ };
@@ -1,70 +1,76 @@
1
- import { Request, RequestHandler, Response } from 'express'
2
- import { errorHandler } from './utils/errorHandler'
1
+ import type { Request, RequestHandler, Response } from 'express';
2
+ import { errorHandler } from './utils/errorHandler.js';
3
3
 
4
4
  export type TransformChunk = (
5
5
  chunk: string | Buffer,
6
6
  encoding: string | null,
7
7
  request: Request,
8
- response: Response
9
- ) => void | string | Buffer | Promise<void> | Promise<string> | Promise<Buffer>
8
+ response: Response,
9
+ ) => void | string | Buffer | Promise<void> | Promise<string> | Promise<Buffer>;
10
10
 
11
11
  export const writeMiddleware =
12
12
  (fn: TransformChunk): RequestHandler =>
13
13
  (req, res, next) => {
14
- const originalWrite = res.write
15
- const originalEndFn = res.end
14
+ const originalWrite = res.write;
15
+ const originalEndFn = res.end;
16
16
 
17
17
  res.write = function (this: Response, chunk) {
18
- if (res.writableEnded) return false
18
+ if (res.writableEnded) return false;
19
19
 
20
- let mayBePromise
20
+ let mayBePromise: ReturnType<TransformChunk>;
21
21
  try {
22
22
  mayBePromise = fn(
23
23
  chunk,
24
24
  // Since `encoding` is an optional argument to `res.write`,
25
25
  // make sure it is a string and not actually the callback.
26
+ // biome-ignore lint/style/noArguments: pass argument type
26
27
  typeof arguments[1] === 'string' ? arguments[1] : null,
27
28
  req,
28
- res
29
- )
29
+ res,
30
+ );
30
31
  } catch (e) {
31
- errorHandler(e, req, res, next)
32
- return false
32
+ errorHandler(e, req, res, next);
33
+ return false;
33
34
  }
34
35
 
35
36
  if (mayBePromise instanceof Promise) {
36
- mayBePromise.then(result => {
37
- try {
38
- res.end = originalEndFn
37
+ mayBePromise
38
+ .then((result) => {
39
+ res.end = originalEndFn;
39
40
 
40
- if (res.writableEnded) return false
41
+ if (res.writableEnded) return false;
41
42
 
42
- arguments[0] = result === undefined ? chunk : result
43
+ // biome-ignore lint/style/noArguments: pass argument type
44
+ arguments[0] = result === undefined ? chunk : result;
43
45
 
44
- const writeResponse = originalWrite.apply(res, arguments as any)
46
+ // biome-ignore lint/style/noArguments: pass argument type
47
+ const writeResponse = originalWrite.apply(res, arguments as any);
45
48
 
46
- if (res.__isEnd) res.end()
49
+ if (res.__isEnd) res.end();
47
50
 
48
- return writeResponse
49
- } catch (e) {
50
- errorHandler(e, req, res, next)
51
- return false
52
- }
53
- })
51
+ return writeResponse;
52
+ })
53
+ .catch((e) => {
54
+ res.end = originalEndFn;
55
+ errorHandler(e, req, res, next);
56
+ });
54
57
 
55
58
  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)
59
+ this.__isEnd = true;
60
+ return res;
61
+ };
62
+ return false;
66
63
  }
67
- }
68
64
 
69
- next()
70
- }
65
+ const result = mayBePromise;
66
+ if (res.writableEnded) return false;
67
+
68
+ // biome-ignore lint/style/noArguments: pass argument type
69
+ arguments[0] = result === undefined ? chunk : result;
70
+
71
+ // biome-ignore lint/style/noArguments: pass argument type
72
+ return originalWrite.apply(res, arguments as any);
73
+ };
74
+
75
+ next();
76
+ };
package/tsconfig.json CHANGED
@@ -22,7 +22,7 @@
22
22
  "noImplicitOverride": true,
23
23
  "noImplicitReturns": true,
24
24
  "noUnusedLocals": true,
25
- "noUnusedParameters": true,
25
+ "noUnusedParameters": true
26
26
  },
27
27
  "include": ["src"]
28
28
  }
package/vitest.config.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { defineConfig } from 'vitest/config'
1
+ import { defineConfig } from 'vitest/config';
2
2
 
3
3
  export default defineConfig({
4
4
  test: {
@@ -11,4 +11,4 @@ export default defineConfig({
11
11
  exclude: ['**/tests/**', '**/*.d.ts'],
12
12
  },
13
13
  },
14
- })
14
+ });
package/.prettierrc.json DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "singleQuote": true,
3
- "tabWidth": 2,
4
- "semi": false,
5
- "trailingComma": "es5",
6
- "bracketSpacing": true,
7
- "arrowParens": "avoid"
8
- }
@@ -1,24 +0,0 @@
1
- import { Request, Response, RequestHandler } from 'express';
2
-
3
- type TransformJson<T = {}> = (body: T, request: Request, response: Response) => unknown | Promise<unknown>;
4
- declare const jsonMiddleware: (fn: TransformJson) => RequestHandler;
5
-
6
- type TransformEnd = (request: Request, response: Response) => unknown | Promise<unknown>;
7
- declare const endMiddleware: (fn: TransformEnd) => RequestHandler;
8
-
9
- type TransformChunk = (chunk: string | Buffer, encoding: string | null, request: Request, response: Response) => void | string | Buffer | Promise<void> | Promise<string> | Promise<Buffer>;
10
- declare const writeMiddleware: (fn: TransformChunk) => RequestHandler;
11
-
12
- type TransformJsonp<T = {}> = (body: T, request: Request, response: Response) => unknown | Promise<unknown>;
13
- declare const jsonpMiddleware: (fn: TransformJsonp) => RequestHandler;
14
-
15
- declare global {
16
- namespace Express {
17
- interface Response {
18
- __isEnd?: boolean;
19
- __isHooked?: boolean;
20
- }
21
- }
22
- }
23
-
24
- export { type TransformChunk, type TransformEnd, type TransformJson, type TransformJsonp, endMiddleware, jsonMiddleware, jsonpMiddleware, writeMiddleware };
package/index.d.ts DELETED
@@ -1,69 +0,0 @@
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