-
Notifications
You must be signed in to change notification settings - Fork 47
/
response.js
184 lines (146 loc) · 4.64 KB
/
response.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
'use strict'
const http = require('node:http')
const { Writable } = require('node:stream')
const util = require('node:util')
const setCookie = require('set-cookie-parser')
function Response (req, onEnd, reject) {
http.ServerResponse.call(this, req)
this._lightMyRequest = { headers: null, trailers: {}, payloadChunks: [] }
// This forces node@8 to always render the headers
this.setHeader('foo', 'bar'); this.removeHeader('foo')
this.assignSocket(getNullSocket())
this._promiseCallback = typeof reject === 'function'
let called = false
const onEndSuccess = (payload) => {
// no need to early-return if already called because this handler is bound `once`
called = true
if (this._promiseCallback) {
return process.nextTick(() => onEnd(payload))
}
process.nextTick(() => onEnd(null, payload))
}
const onEndFailure = (err) => {
if (called) return
called = true
if (this._promiseCallback) {
return process.nextTick(() => reject(err))
}
process.nextTick(() => onEnd(err, null))
}
this.once('finish', () => {
const res = generatePayload(this)
res.raw.req = req
onEndSuccess(res)
})
this.connection.once('error', onEndFailure)
this.once('error', onEndFailure)
this.once('close', onEndFailure)
}
util.inherits(Response, http.ServerResponse)
Response.prototype.setTimeout = function (msecs, callback) {
this.timeoutHandle = setTimeout(() => {
this.emit('timeout')
}, msecs)
this.on('timeout', callback)
return this
}
Response.prototype.writeHead = function () {
const result = http.ServerResponse.prototype.writeHead.apply(this, arguments)
copyHeaders(this)
return result
}
Response.prototype.write = function (data, encoding, callback) {
if (this.timeoutHandle) {
clearTimeout(this.timeoutHandle)
}
http.ServerResponse.prototype.write.call(this, data, encoding, callback)
this._lightMyRequest.payloadChunks.push(Buffer.from(data, encoding))
return true
}
Response.prototype.end = function (data, encoding, callback) {
if (data) {
this.write(data, encoding)
}
http.ServerResponse.prototype.end.call(this, callback)
this.emit('finish')
// We need to emit 'close' otherwise stream.finished() would
// not pick it up on Node v16
this.destroy()
}
Response.prototype.destroy = function (error) {
if (this.destroyed) return
this.destroyed = true
if (error) {
process.nextTick(() => this.emit('error', error))
}
process.nextTick(() => this.emit('close'))
}
Response.prototype.addTrailers = function (trailers) {
for (const key in trailers) {
this._lightMyRequest.trailers[key.toLowerCase().trim()] = trailers[key].toString().trim()
}
}
function generatePayload (response) {
// This seems only to happen when using `fastify-express` - see https://github.com/fastify/fastify-express/issues/47
/* istanbul ignore if */
if (response._lightMyRequest.headers === null) {
copyHeaders(response)
}
serializeHeaders(response)
// Prepare response object
const res = {
raw: {
res: response
},
headers: response._lightMyRequest.headers,
statusCode: response.statusCode,
statusMessage: response.statusMessage,
trailers: {},
get cookies () {
return setCookie.parse(this)
}
}
// Prepare payload and trailers
const rawBuffer = Buffer.concat(response._lightMyRequest.payloadChunks)
res.rawPayload = rawBuffer
// we keep both of them for compatibility reasons
res.payload = rawBuffer.toString()
res.body = res.payload
res.trailers = response._lightMyRequest.trailers
// Prepare payload parsers
res.json = function parseJsonPayload () {
return JSON.parse(res.payload)
}
return res
}
// Throws away all written data to prevent response from buffering payload
function getNullSocket () {
return new Writable({
write (chunk, encoding, callback) {
setImmediate(callback)
}
})
}
function serializeHeaders (response) {
const headers = response._lightMyRequest.headers
for (const headerName of Object.keys(headers)) {
const headerValue = headers[headerName]
if (Array.isArray(headerValue)) {
headers[headerName] = headerValue.map(value => '' + value)
} else {
headers[headerName] = '' + headerValue
}
}
}
function copyHeaders (response) {
response._lightMyRequest.headers = Object.assign({}, response.getHeaders())
// Add raw headers
;['Date', 'Connection', 'Transfer-Encoding'].forEach((name) => {
const regex = new RegExp('\\r\\n' + name + ': ([^\\r]*)\\r\\n')
const field = response._header.match(regex)
if (field) {
response._lightMyRequest.headers[name.toLowerCase()] = field[1]
}
})
}
module.exports = Response