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 pathcreateRequestObject.js
81 lines (64 loc) · 1.88 KB
/
createRequestObject.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");
const queryString = require("querystring");
const http = require("http");
// Mock a HTTP IncomingMessage object from the Netlify Function event parameters
// 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 createRequestObject = ({ event }) => {
const {
requestContext = {},
path = "",
multiValueQueryStringParameters,
pathParameters,
httpMethod,
multiValueHeaders = {},
body,
isBase64Encoded,
} = event;
const newStream = new Stream.Readable();
const req = Object.assign(newStream, http.IncomingMessage.prototype);
req.url =
(requestContext.path || path || "").replace(
new RegExp("^/" + requestContext.stage),
""
) || "/";
let qs = "";
if (multiValueQueryStringParameters) {
qs += queryString.stringify(multiValueQueryStringParameters);
}
if (pathParameters) {
const pathParametersQs = queryString.stringify(pathParameters);
if (qs.length > 0) {
qs += `&${pathParametersQs}`;
} else {
qs += pathParametersQs;
}
}
const hasQueryString = qs.length > 0;
if (hasQueryString) {
req.url += `?${qs}`;
}
req.method = httpMethod;
req.rawHeaders = [];
req.headers = {};
for (const key of Object.keys(multiValueHeaders)) {
for (const value of multiValueHeaders[key]) {
req.rawHeaders.push(key);
req.rawHeaders.push(value);
}
req.headers[key.toLowerCase()] = multiValueHeaders[key].toString();
}
req.getHeader = (name) => {
return req.headers[name.toLowerCase()];
};
req.getHeaders = () => {
return req.headers;
};
req.connection = {};
if (body) {
req.push(body, isBase64Encoded ? "base64" : undefined);
}
req.push(null);
return req;
};
module.exports = createRequestObject;