forked from getndazn/dazn-lambda-powertools
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
50 lines (42 loc) · 1.37 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
const Log = require('@dazn/lambda-powertools-logger')
const createTimer = (event, context, thresholdMillis) => {
if (typeof context.getRemainingTimeInMillis !== 'function') {
return null
}
const timeLeft = context.getRemainingTimeInMillis()
const timeoutMs = timeLeft - thresholdMillis
const timer = setTimeout(() => {
const awsRequestId = context.awsRequestId
const invocationEvent = JSON.stringify(event)
Log.error('invocation timed out', { awsRequestId, invocationEvent })
}, timeoutMs)
return timer
}
const hasTimer = (context) => {
return context.lambdaPowertoolsLogTimeoutMiddleware &&
context.lambdaPowertoolsLogTimeoutMiddleware.timer
}
module.exports = (thresholdMillis = 10) => {
return {
before: (handler, next) => {
const timer = createTimer(handler.event, handler.context, thresholdMillis)
Object.defineProperty(handler.context, 'lambdaPowertoolsLogTimeoutMiddleware', {
enumerable: false,
value: { timer }
})
next()
},
after: (handler, next) => {
if (hasTimer(handler.context)) {
clearTimeout(handler.context.lambdaPowertoolsLogTimeoutMiddleware.timer)
}
next()
},
onError: (handler, next) => {
if (hasTimer(handler.context)) {
clearTimeout(handler.context.lambdaPowertoolsLogTimeoutMiddleware.timer)
}
next(handler.error)
}
}
}