-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
93 lines (76 loc) · 2.37 KB
/
index.js
File metadata and controls
93 lines (76 loc) · 2.37 KB
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
'use strict';
class LambdaProxyResponse {
constructor(options) {
this.options = options || { headers: {}, body: {}, status: null, extendHeader: true };
}
config(options) {
if (typeof options === 'object' && options !== null) {
Object.assign(this.options, options);
}
}
response(status, headers, body, cb, options) {
let responseStatus = {};
let responseHeader = {};
let responseBody = {};
responseStatus = status || this.options.status || 400;
// set headers
if (typeof headers !== 'object' || headers === null ) {
if (this.options && this.options.headers) {
responseHeader = this.options.headers;
} else {
responseHeader = {};
}
} else {
if (this.options.headers && this.options.extendHeader) {
responseHeader = Object.assign(responseHeader, headers, this.options.headers);
} else {
responseHeader = headers;
}
}
// set body
if (typeof body === 'undefined' || body === null) {
if (this.options && this.options.body) {
responseBody = this.options.body;
} else {
responseBody = {};
}
} else {
responseBody = body;
}
const responseTemplate = this._createResponseTemplate(responseStatus, responseHeader, responseBody);
// call cb
if (typeof cb === 'function') {
cb(null, responseTemplate);
}
return responseTemplate;
}
ok(headers, body, cb, options) {
return this.response(200, headers, body, cb, options || {});
}
created(headers, body, cb, options) {
return this.response(201, headers, body, cb, options || {});
}
badRequest(headers, body, cb, options) {
return this.response(400, headers, body, cb, options || {});
}
notAuthorized(headers, body, cb, options) {
return this.response(401, headers, body, cb, options || {});
}
forbidden(headers, body, cb, options) {
return this.response(403, headers, body, cb, options || {});
}
notFound(headers, body, cb, options) {
return this.response(404, headers, body, cb, options || {});
}
serverError(headers, body, cb, options) {
return this.response(500, headers, body, cb, options || {});
}
_createResponseTemplate(status, headers, body) {
return {
statusCode: status,
body: JSON.stringify(body),
headers: headers
};
}
}
module.exports = new LambdaProxyResponse();