-
Notifications
You must be signed in to change notification settings - Fork 163
/
response.js
132 lines (104 loc) 路 2.88 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
'use strict';
const http = require('http');
const headerEnd = '\r\n\r\n';
const BODY = Symbol();
const HEADERS = Symbol();
function getString(data) {
if (Buffer.isBuffer(data)) {
return data.toString('utf8');
} else if (typeof data === 'string') {
return data;
} else {
throw new Error(`response.write() of unexpected type: ${typeof data}`);
}
}
function addData(stream, data) {
if (Buffer.isBuffer(data) || typeof data === 'string' || data instanceof Uint8Array) {
stream[BODY].push(Buffer.from(data));
} else {
throw new Error(`response.write() of unexpected type: ${typeof data}`);
}
}
module.exports = class ServerlessResponse extends http.ServerResponse {
static from(res) {
const response = new ServerlessResponse(res);
response.statusCode = res.statusCode
response[HEADERS] = res.headers;
response[BODY] = [Buffer.from(res.body)];
response.end();
return response;
}
static body(res) {
return Buffer.concat(res[BODY]);
}
static headers(res) {
const headers = typeof res.getHeaders === 'function'
? res.getHeaders()
: res._headers;
return Object.assign(headers, res[HEADERS]);
}
get headers() {
return this[HEADERS];
}
setHeader(key, value) {
if (this._wroteHeader) {
this[HEADERS][key] = value;
} else {
super.setHeader(key, value);
}
}
writeHead(statusCode, reason, obj) {
const headers = typeof reason === 'string'
? obj
: reason
for (const name in headers) {
this.setHeader(name, headers[name])
if (!this._wroteHeader) {
// we only need to initiate super.headers once
// writeHead will add the other headers itself
break
}
}
super.writeHead(statusCode, reason, obj);
}
constructor({ method }) {
super({ method });
this[BODY] = [];
this[HEADERS] = {};
this.useChunkedEncodingByDefault = false;
this.chunkedEncoding = false;
this._header = '';
this.assignSocket({
_writableState: {},
writable: true,
on: Function.prototype,
removeListener: Function.prototype,
destroy: Function.prototype,
cork: Function.prototype,
uncork: Function.prototype,
write: (data, encoding, cb) => {
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (this._header === '' || this._wroteHeader) {
addData(this, data);
} else {
const string = getString(data);
const index = string.indexOf(headerEnd);
if (index !== -1) {
const remainder = string.slice(index + headerEnd.length);
if (remainder) {
addData(this, remainder);
}
this._wroteHeader = true;
}
}
if (typeof cb === 'function') {
cb();
}
return true;
},
});
}
};