-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsim-lambda-runtime-provided-sdk.example.ts
More file actions
90 lines (81 loc) · 2.47 KB
/
Copy pathsim-lambda-runtime-provided-sdk.example.ts
File metadata and controls
90 lines (81 loc) · 2.47 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
/**
* Simulated Lambda function code reading sim S3 through the
* runtime-provided AWS SDK, authorized as its execution role.
*/
import { CreateRoleCommand, PutRolePolicyCommand } from "@aws-sdk/client-iam";
import { CreateFunctionCommand, InvokeCommand } from "@aws-sdk/client-lambda";
import { CreateBucketCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { SimAws } from "@kensio/yulin";
import { makeLambdaCodeZip } from "@kensio/yulin/lambda";
const simAws = new SimAws();
// An object for the function to read.
await simAws
.s3()
.createBucket(new CreateBucketCommand({ Bucket: "data-bucket" }));
await simAws.s3().putObject(
new PutObjectCommand({
Bucket: "data-bucket",
Key: "greeting.txt",
Body: "Hello from S3",
}),
);
// An execution role allowed to read it.
const roleCreation = await simAws.iam().createRole(
new CreateRoleCommand({
RoleName: "ReaderRole",
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: "ReaderRole",
PolicyName: "ReadDataBucket",
PolicyDocument: JSON.stringify({
Version: "2012-10-17",
Statement: {
Effect: "Allow",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::data-bucket/*",
},
}),
}),
);
// Function code using the runtime-provided AWS SDK.
await simAws.lambda().createFunction(
new CreateFunctionCommand({
FunctionName: "reader",
Role: roleCreation.Role.Arn,
Handler: "index.handler",
Code: {
ZipFile: makeLambdaCodeZip(`
const { S3Client, GetObjectCommand } = require("@aws-sdk/client-s3");
const s3Client = new S3Client({});
exports.handler = async (event) => {
const output = await s3Client.send(
new GetObjectCommand({
Bucket: "data-bucket",
Key: event.objectKey,
}),
);
return await output.Body.transformToString();
};
`),
},
}),
);
const output = await simAws.lambda().invoke(
new InvokeCommand({
FunctionName: "reader",
Payload: JSON.stringify({ objectKey: "greeting.txt" }),
}),
);
if (output.Payload === undefined) throw new Error("No invoke Payload");
console.log(Buffer.from(output.Payload).toString());
await simAws.backgroundTasksComplete();