-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AutoHeadersMiddleware.js
73 lines (66 loc) · 2.03 KB
/
AutoHeadersMiddleware.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/** @typedef {import('../lib/HttpResponse.js').default} HttpResponse */
/** @typedef {import('../types').ResponseFinalizer} ResponseFinalizer */
/** @typedef {import('../types').MiddlewareFunction} MiddlewareFunction */
import { Transform } from 'node:stream';
/**
* @typedef {Object} AutoHeadersMiddlewareOptions
* @prop {boolean} [setStatus=true]
* Automatically set `200` or `204` status if not set
*/
export default class AutoHeadersMiddleware {
/** @param {AutoHeadersMiddlewareOptions} options */
constructor(options = {}) {
this.setStatus = options.setStatus !== false;
this.finalizeResponse = this.finalizeResponse.bind(this);
}
/**
* @param {HttpResponse} response
* @return {void}
*/
addTransformStream(response) {
let firstChunk = false;
response.pipes.push(new Transform({
transform: (chunk, encoding, callback) => {
if (!firstChunk) {
firstChunk = true;
if (!response.headersSent) {
if (response.statusCode == null) {
if (!this.setStatus) {
callback(new Error('NO_STATUS'));
return;
}
response.status = 200;
}
response.sendHeaders(false);
}
}
callback(null, chunk);
},
final: (callback) => {
if (!response.headersSent) {
if (this.setStatus && response.statusCode == null) {
response.status = 204;
}
response.sendHeaders(false);
}
callback();
},
}));
}
/** @type {ResponseFinalizer} */
finalizeResponse(response) {
if (response.headersSent) return;
if (response.isStreaming) {
this.addTransformStream(response);
return;
}
if (response.status == null && this.setStatus && Buffer.isBuffer(response.body)) {
response.status = response.body.byteLength ? 200 : 204;
}
response.sendHeaders();
}
/** @type {MiddlewareFunction} */
execute({ response }) {
response.finalizers.push(this.finalizeResponse);
}
}