This repository has been archived by the owner on Nov 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqs.ts
56 lines (46 loc) · 1.49 KB
/
sqs.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
import {
SQSRecord,
SQSHandler,
Callback,
SQSBatchResponse,
Context,
SQSEvent
} from 'aws-lambda'
type Result =
| { retry: true }
| { retry: false }
export function retry(): Result {
return { retry: true }
}
export function pass(): Result {
return { retry: false }
}
type HandlerFunction =
(
record: SQSRecord,
context: Context,
callback: Callback<void | SQSBatchResponse>
) => Promise<Result> | Result
type ProcessRecordOutput = { record: SQSRecord, result: Result }
const processRecord =
(fn: HandlerFunction, context: Context, callback: Callback<void | SQSBatchResponse>) =>
async (record: SQSRecord): Promise<ProcessRecordOutput> => {
const output = await Promise.resolve(fn(record, context, callback))
return { record, result: output }
}
const processEvent =
(fn: HandlerFunction, event: SQSEvent, context: Context, callback: Callback<void | SQSBatchResponse>) =>
event.Records.map(processRecord(fn, context, callback))
const filterRetriedRecords = (outputs: ProcessRecordOutput[]) =>
outputs.filter(({ result }) => result.retry)
const mapToBatchResponse = (outputs: ProcessRecordOutput[]): SQSBatchResponse => ({
batchItemFailures: outputs.map(({ record }) => ({
itemIdentifier: record.messageId
}))
})
export const makeHandler =
(fn: HandlerFunction): SQSHandler =>
(event, context, callback) =>
Promise.all(processEvent(fn, event, context, callback))
.then(filterRetriedRecords)
.then(mapToBatchResponse)