/
index.js
98 lines (81 loc) · 2.09 KB
/
index.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
'use strict';
const CONTENT_TYPE_REGEXP = /^[A-Za-z-]+$/;
class AWSLambdaProxyResponse {
constructor(statusCode) {
// default HTTP status to 200/OK if not given
this.setStatusCode(
(statusCode === undefined)
? AWSLambdaProxyResponse.HTTP_STATUS.OK
: statusCode
);
// empty headers and body
this.headerCollection = {};
this.body = '';
}
setStatusCode(statusCode) {
// is HTTP code valid?
const statusCollection = AWSLambdaProxyResponse.HTTP_STATUS,
isValid = Object.keys(statusCollection).some((statusName) => {
return (statusCollection[statusName] === statusCode);
});
if (!isValid) {
throw new Error(`Invalid HTTP status code [${statusCode}] given`);
}
// all good
this.statusCode = statusCode;
return this;
}
addHeader(name,value) {
// assume name contains a header collection
let addHeaderCollection = name;
if (value !== undefined) {
// adding a single header only
addHeaderCollection = {
[name]: value
};
}
// validate all header names
const headerKeyList = Object.keys(addHeaderCollection);
for (const headerName of headerKeyList) {
if (!CONTENT_TYPE_REGEXP.test(headerName)) {
throw new Error(`Invalid HTTP header name of [${headerName}] given`);
break;
}
}
// with all header names validated, add into response
for (const headerName of headerKeyList) {
this.headerCollection[headerName] = addHeaderCollection[headerName].trim();
}
return this;
}
setBody(body) {
// if body isn't a string, we use JSON.stringify() to serialize
this.body = (typeof body == 'string')
? body
: JSON.stringify(body);
return this;
}
getPayload() {
return {
statusCode: this.statusCode,
headers: this.headerCollection,
body: this.body
};
}
}
// note: only HTTP status codes of frequent use/lazy
AWSLambdaProxyResponse.HTTP_STATUS = {
OK: 200,
MOVED: 301,
FOUND: 302,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
SERVER_ERROR: 500,
NOT_IMPLEMENTED: 501,
BAD_GATEWAY: 502,
SERVICE_UNAVAILABLE: 503,
GATEWAY_TIMEOUT: 504
};
module.exports = AWSLambdaProxyResponse;