-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy pathrequest.js
68 lines (57 loc) · 1.89 KB
/
request.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
'use strict';
const http = require('http');
const url = require('url');
function getHeaders(event) {
return Object.keys(event.headers).reduce((headers, key) => {
headers[key.toLowerCase()] = event.headers[key];
return headers;
}, {});
}
function getBody(event, headers) {
if (typeof event.body === 'string') {
return Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8');
} else if (Buffer.isBuffer(event.body)) {
return event.body;
} else if (typeof event.body === 'object') {
const contentType = headers['content-type'];
if (contentType && contentType.indexOf('application/json') === 0) {
return Buffer.from(JSON.stringify(event.body));
} else {
throw new Error('event.body was an object but content-type is not json');
}
}
throw new Error(`Unexpected event.body type: ${typeof event.body}`);
}
module.exports = class ServerlessRequest extends http.IncomingMessage {
constructor(event, options) {
super({
encrypted: true,
readable: false,
remoteAddress: event.requestContext.identity.sourceIp
});
const headers = getHeaders(event);
const body = getBody(event, headers);
if (typeof headers['content-length'] === 'undefined') {
headers['content-length'] = Buffer.byteLength(body);
}
if (typeof options.requestId === 'string' && options.requestId.length > 0) {
const requestId = options.requestId.toLowerCase();
headers[requestId] = headers[requestId] || event.requestContext.requestId;
}
Object.assign(this, {
ip: event.requestContext.identity.sourceIp,
complete: true,
httpVersion: '1.1',
httpVersionMajor: '1',
httpVersionMinor: '1',
method: event.httpMethod,
headers: headers,
url: url.format({
pathname: event.path,
query: event.queryStringParameters
})
});
this.push(body);
this.push(null);
}
}