This repository has been archived by the owner on Oct 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguard.ts
63 lines (56 loc) · 1.87 KB
/
guard.ts
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
import { setupLogger, Logger } from '@episodehunter/logger'
import { Context, Callback } from 'aws-lambda'
type EventType = { [key: string]: any }
function createGuard(ravenDsn?: string, logdnaKey?: string, _setupLogger = setupLogger) {
const createLogger = _setupLogger(ravenDsn, logdnaKey)
return function guard<T extends EventType>(
fun: (event: T, logger: Logger, context: Context) => any
) {
return async (event: T | string, context: Context, callback: Callback) => {
let parsedEvent!: T
try {
parsedEvent = parseEvent(event);
} catch (error) {
return callback(error)
}
let requestStack: string[] | undefined
if (parsedEvent && parsedEvent.headers) {
requestStack = extractRequestStackFromHeader(parsedEvent)
} else if (event && parsedEvent.requestStack) {
requestStack = parsedEvent.requestStack
}
const logger = createLogger(context, requestStack)
const timeoutId = setTimeout(() => {
logger.captureException(new Error(`Timeout in 500ms for ${context.functionName}`))
}, context.getRemainingTimeInMillis() - 500)
try {
callback(undefined, await fun(parsedEvent, logger, context))
} catch (error) {
logger.captureException(error)
callback(error)
} finally {
clearTimeout(timeoutId)
}
}
}
}
function parseEvent<T>(event: T | string): T {
if (typeof event === 'string') {
try {
return JSON.parse(event);
} catch (error) {
console.error('Could not parse ' + event);
throw error;
}
} else {
return event
}
}
function extractRequestStackFromHeader(event: { headers?: { [key: string]: string } }): string[] | undefined {
if (!event.headers) {
return
}
const requestStack = event.headers['x-request-stack'] || ''
return requestStack.split(',')
}
export { Logger, createGuard }