-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsim-lambda-sqs-event-source.example.ts
More file actions
90 lines (78 loc) · 2.3 KB
/
Copy pathsim-lambda-sqs-event-source.example.ts
File metadata and controls
90 lines (78 loc) · 2.3 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
90
/**
* Delivering messages from a simulated queue to a simulated function.
*/
import { CreateRoleCommand, PutRolePolicyCommand } from "@aws-sdk/client-iam";
import {
CreateEventSourceMappingCommand,
CreateFunctionCommand,
} from "@aws-sdk/client-lambda";
import { CreateQueueCommand, SendMessageCommand } from "@aws-sdk/client-sqs";
import { SimAws } from "@kensio/yulin";
import {
makeLambdaZipFileInput,
type SimLambdaSqsEvent,
} from "@kensio/yulin/lambda";
const simAws = new SimAws();
const queueArn = `arn:aws:sqs:${simAws.defaultRegionName}:${simAws.defaultAccountId}:orders`;
const { QueueUrl } = await simAws
.sqs()
.createQueue(new CreateQueueCommand({ QueueName: "orders" }));
// The execution role needs the three SQS actions Lambda polls a queue with.
const role = await simAws.iam().createRole(
new CreateRoleCommand({
RoleName: "OrderConsumerRole",
AssumeRolePolicyDocument: JSON.stringify({
Version: "2012-10-17",
Statement: {
Effect: "Allow",
Principal: { Service: "lambda.amazonaws.com" },
Action: "sts:AssumeRole",
},
}),
}),
);
await simAws.iam().putRolePolicy(
new PutRolePolicyCommand({
RoleName: "OrderConsumerRole",
PolicyName: "ConsumeOrders",
PolicyDocument: JSON.stringify({
Version: "2012-10-17",
Statement: {
Effect: "Allow",
Action: [
"sqs:ReceiveMessage",
"sqs:DeleteMessage",
"sqs:GetQueueAttributes",
],
Resource: queueArn,
},
}),
}),
);
const consumed: string[] = [];
await simAws.lambda().createFunction(
new CreateFunctionCommand({
FunctionName: "order-consumer",
Role: role.Role.Arn,
Code: {
ZipFile: makeLambdaZipFileInput((event: SimLambdaSqsEvent) => {
for (const record of event.Records) {
consumed.push(record.body);
}
}),
},
}),
);
await simAws.lambda().createEventSourceMapping(
new CreateEventSourceMappingCommand({
EventSourceArn: queueArn,
FunctionName: "order-consumer",
BatchSize: 5,
}),
);
await simAws
.sqs()
.sendMessage(new SendMessageCommand({ QueueUrl, MessageBody: "order-1" }));
// Delivery happens in the background, so wait for the simulation to settle.
await simAws.backgroundTasksComplete();
console.log(consumed); // ["order-1"]