forked from middyjs/middy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
78 lines (71 loc) · 2.19 KB
/
index.js
File metadata and controls
78 lines (71 loc) · 2.19 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
const inputOutputLoggerMiddleware = (opts = {}) => {
const defaults = {
logger: (data) => console.log(JSON.stringify(data, null, 2)),
awsContext: false,
omitPaths: []
}
let { logger, awsContext, omitPaths } = { ...defaults, ...opts }
if (typeof logger !== 'function') logger = null
const omitAndLog = (param, request) => {
const message = {
[param]: request[param]
}
if (awsContext) {
message.context = pick(request.context, awsContextKeys)
}
const redactedMessage = omit(JSON.parse(JSON.stringify(message)), omitPaths) // Full clone to prevent nested mutations
logger(redactedMessage)
}
const inputOutputLoggerMiddlewareBefore = async (request) =>
omitAndLog('event', request)
const inputOutputLoggerMiddlewareAfter = async (request) =>
omitAndLog('response', request)
const inputOutputLoggerMiddlewareOnError = inputOutputLoggerMiddlewareAfter
return {
before: logger ? inputOutputLoggerMiddlewareBefore : undefined,
after: logger ? inputOutputLoggerMiddlewareAfter : undefined,
onError: logger ? inputOutputLoggerMiddlewareOnError : undefined
}
}
// https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html
const awsContextKeys = [
'functionName',
'functionVersion',
'invokedFunctionArn',
'memoryLimitInMB',
'awsRequestId',
'logGroupName',
'logStreamName',
'identity',
'clientContext',
'callbackWaitsForEmptyEventLoop'
]
// move to util, if ever used elsewhere
const pick = (originalObject = {}, keysToPick = []) => {
const newObject = {}
for (const path of keysToPick) {
// only supports first level
if (originalObject[path] !== undefined) {
newObject[path] = originalObject[path]
}
}
return newObject
}
const omit = (originalObject = {}, keysToOmit = []) => {
const clonedObject = { ...originalObject }
for (const path of keysToOmit) {
deleteKey(clonedObject, path)
}
return clonedObject
}
const deleteKey = (obj, key) => {
if (!Array.isArray(key)) key = key.split('.')
const rootKey = key.shift()
if (key.length && obj[rootKey]) {
deleteKey(obj[rootKey], key)
} else {
delete obj[rootKey]
}
return obj
}
module.exports = inputOutputLoggerMiddleware