-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.ts
66 lines (56 loc) · 1.96 KB
/
context.ts
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
import { Context, ServerlessEvent } from './types';
import ServerlessRequest from './serverlessRequest';
import url from 'node:url';
import { debug } from './common';
// const requestRemoteAddress = (event) => {
// if (event.version === '2.0') {
// return event.requestContext.http.sourceIp;
// }
// return event.requestContext.identity.sourceIp;
// };
const requestBody = (event: ServerlessEvent) => {
if (!event.body) {
return undefined;
}
const type = typeof event.body;
if (Buffer.isBuffer(event.body)) {
return event.body;
} else if (type === 'string') {
return Buffer.from(event.body as string, event.isBase64Encoded ? 'base64' : 'utf8');
} else if (type === 'object') {
return Buffer.from(JSON.stringify(event.body));
}
throw new Error(`Unexpected event.body type: ${typeof event.body}`);
};
const requestHeaders = (event: ServerlessEvent) => {
const initialHeader = {} as Record<string, string>;
// if (event.multiValueHeaders) {
// Object.keys(event.multiValueHeaders).reduce((headers, key) => {
// headers[key.toLowerCase()] = event.multiValueHeaders[key].join(', ');
// return headers;
// }, initialHeader);
// }
return Object.keys(event.headers ?? {}).reduce((headers, key) => {
headers[key.toLowerCase()] = event.headers[key];
return headers;
}, initialHeader);
};
export const constructFrameworkContext = (rawEvent: Buffer, rawContext: Context) => {
debug(`constructFrameworkContext: ${JSON.stringify({ rawEvent, rawContext })}`);
const event = JSON.parse(Buffer.from(rawEvent).toString()) as ServerlessEvent;
const body = requestBody(event);
const headers = requestHeaders(event);
const request = new ServerlessRequest({
method: event.httpMethod,
path: event.path,
headers,
body,
remoteAddress: '',
url: url.format({
pathname: event.path,
query: event.queryParameters,
}),
isBase64Encoded: event.isBase64Encoded,
});
return { request };
};