-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
89 lines (78 loc) · 2.51 KB
/
index.js
File metadata and controls
89 lines (78 loc) · 2.51 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
const url = require('url')
const querystring = require('querystring')
const formatHeaders = (options, responseHeaders = {}) => {
return Object.assign({}, options.headers, responseHeaders)
}
const formatBody = (body) => {
if (!body) {
return ''
}
if (typeof body === 'string') {
return body
}
return JSON.stringify(body)
}
const isLambdaResponse = (response) => {
return response &&
typeof response === 'object' &&
['statusCode', 'body', 'headers'].find(f => Object.prototype.hasOwnProperty.call(response, f))
}
const DEFAULT_STATUS_CODE = 200
const formatResponse = (response, options) => {
if (isLambdaResponse(response)) {
return {
statusCode: Number.parseInt(response.statusCode) || DEFAULT_STATUS_CODE,
body: formatBody(response.body),
headers: formatHeaders(options, response.headers)
}
}
return {
statusCode: DEFAULT_STATUS_CODE,
body: formatBody(response),
headers: formatHeaders(options)
}
}
const formatFilterParameter = (requestId) => querystring.escape(`"${requestId}"`)
const createLogLink = (context) => url.format({
protocol: 'https',
host: `${process.env.AWS_REGION}.console.aws.amazon.com`,
pathname: '/cloudwatch/home',
search: `region=${process.env.AWS_REGION}`,
hash: `logEventViewer:group=${process.env.AWS_LAMBDA_LOG_GROUP_NAME};filter=${formatFilterParameter(context.awsRequestId)}`
})
const requestErrorHandler = (context, options) => (error) => {
if (options.logErrors) {
console.error(error)
}
return {
statusCode: error.code || 500,
body: {
message: options.errorFormatter(error),
log: options.cloudWatchLogLinks ? createLogLink(context) : undefined
}
}
}
const DEFAULT_OPTIONS = {
headers: {
'Access-Control-Allow-Origin': '*'
},
cloudWatchLogLinks: true,
logErrors: true,
errorFormatter: (error) => error.message
}
const createHandler = (delegate, options = {}) => {
if (typeof delegate !== 'function') {
throw new Error('"delegate" must be a function')
}
if (options.hasOwnProperty('errorFormatter') && typeof options.errorFormatter !== 'function') {
throw new Error('"errorFormatter" option must be a function')
}
const combinedOptions = Object.assign({}, DEFAULT_OPTIONS, options)
return (event, context, callback) => {
return Promise.resolve()
.then(() => delegate(event, context))
.catch(requestErrorHandler(context, combinedOptions))
.then((response) => callback(null, formatResponse(response, combinedOptions)))
}
}
module.exports = {createHandler}