This repository was archived by the owner on May 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathcreateResponseObject.js
81 lines (72 loc) · 2.2 KB
/
createResponseObject.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
const Stream = require("stream");
// Mock a HTTP ServerResponse object that returns a Netlify Function-compatible
// response via the onResEnd callback when res.end() is called.
// Based on API Gateway Lambda Compat
// Source: https://github.com/serverless-nextjs/serverless-next.js/blob/master/packages/compat-layers/apigw-lambda-compat/lib/compatLayer.js
const createResponseObject = ({ onResEnd }) => {
const response = {
isBase64Encoded: true,
multiValueHeaders: {},
};
const res = new Stream();
Object.defineProperty(res, "statusCode", {
get() {
return response.statusCode;
},
set(statusCode) {
response.statusCode = statusCode;
},
});
res.headers = {};
res.writeHead = (status, headers) => {
response.statusCode = status;
if (headers) res.headers = Object.assign(res.headers, headers);
};
res.write = (chunk) => {
if (!response.body) {
response.body = Buffer.from("");
}
response.body = Buffer.concat([
Buffer.isBuffer(response.body)
? response.body
: Buffer.from(response.body),
Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk),
]);
};
res.setHeader = (name, value) => {
res.headers[name.toLowerCase()] = value;
};
res.removeHeader = (name) => {
delete res.headers[name.toLowerCase()];
};
res.getHeader = (name) => {
return res.headers[name.toLowerCase()];
};
res.getHeaders = () => {
return res.headers;
};
res.hasHeader = (name) => {
return !!res.getHeader(name);
};
res.end = (text) => {
if (text) res.write(text);
if (!res.statusCode) {
res.statusCode = 200;
}
if (response.body) {
response.body = Buffer.from(response.body).toString("base64");
}
response.multiValueHeaders = res.headers;
res.writeHead(response.statusCode);
// Convert all multiValueHeaders into arrays
for (const key of Object.keys(response.multiValueHeaders)) {
if (!Array.isArray(response.multiValueHeaders[key])) {
response.multiValueHeaders[key] = [response.multiValueHeaders[key]];
}
}
// Call onResEnd handler with the response object
onResEnd(response);
};
return res;
};
module.exports = createResponseObject;