-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrapper.js
71 lines (65 loc) · 1.71 KB
/
wrapper.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
'use strict';
let rfr = require('rfr');
let LambdaError = rfr('errors');
/**
* Wrap a module.exports clause to handle common Lambda handler for statusCode, errors, and body.
* TODO: Add validation based on the swagger method.
*/
function wrapHeaders(res) {
if (typeof res !== 'object') {
console.error('Response is not an object', res);
return res;
}
res.headers = {
'Access-Control-Allow-Origin': '*'
};
return res;
}
function wrapFunction(func) {
return (event, context, callback) => {
try {
func(event).then((data) => {
callback(null, wrapHeaders({
statusCode: 200,
body: JSON.stringify(data)
}))
}).catch((lambdaError) => {
if (lambdaError instanceof LambdaError) {
callback(null, wrapHeaders(lambdaError.toLambda()));
} else {
// An unexpected error occurred, log the error, dont send to user.
console.error('Unexpected error', lambdaError);
callback(null, wrapHeaders({
statusCode: 500,
headers: {
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
message: 'An internal error occurred',
type: 'internalError'
})
}));
}
});
} catch (e) {
console.error('Uncaught exception', e, e.stack);
callback(null, wrapHeaders({
statusCode: 500,
body: JSON.stringify({
message: 'An internal error occurred',
type: 'internalError'
})
}));
}
}
}
function wrapModule(mod) {
let out = {};
for (let key in mod) {
out[key] = wrapFunction(mod[key]);
}
return out;
}
module.exports = {
wrapModule
};