-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.ts
78 lines (73 loc) · 1.82 KB
/
handler.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { newApiGatewayManagementApi } from "@yingyeothon/aws-apigateway-management-api";
import { APIGatewayProxyHandler } from "aws-lambda";
import { ApiGatewayManagementApi, DynamoDB } from "aws-sdk";
if (process.env.NODE_ENV === "development") {
require("source-map-support/register");
}
export const connect: APIGatewayProxyHandler = async event => {
await new DynamoDB()
.putItem({
TableName: `ConnectionIds`,
Item: {
connectionId: { S: event.requestContext.connectionId }
}
})
.promise();
return {
statusCode: 200,
body: "OK"
};
};
export const disconnect: APIGatewayProxyHandler = async event => {
await new DynamoDB()
.deleteItem({
TableName: `ConnectionIds`,
Key: {
connectionId: { S: event.requestContext.connectionId }
}
})
.promise();
return {
statusCode: 200,
body: "OK"
};
};
export const broadcast: APIGatewayProxyHandler = async event => {
if (event.body === "exit") {
await newApiGatewayManagementApi({
endpoint:
event.requestContext.domainName + "/" + event.requestContext.stage
})
.deleteConnection({
ConnectionId: event.requestContext.connectionId
})
.promise();
return {
statusCode: 200,
body: "OK"
};
}
const dbResult = await new DynamoDB()
.scan({
TableName: `ConnectionIds`,
ProjectionExpression: "connectionId"
})
.promise();
const api = new ApiGatewayManagementApi({
endpoint: event.requestContext.domainName + "/" + event.requestContext.stage
});
await Promise.all(
dbResult.Items.map(async ({ connectionId }) =>
api
.postToConnection({
ConnectionId: connectionId.S,
Data: event.body
})
.promise()
)
);
return {
statusCode: 200,
body: "OK"
};
};