forked from anomalyco/sst
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsendMessage.js
More file actions
37 lines (30 loc) · 1.02 KB
/
Copy pathsendMessage.js
File metadata and controls
37 lines (30 loc) · 1.02 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
import AWS from "aws-sdk";
const TableName = process.env.tableName;
const dynamoDb = new AWS.DynamoDB.DocumentClient();
export async function main(event) {
const messageData = JSON.parse(event.body).data;
const { stage, domainName } = event.requestContext;
// Get all the connections
const connections = await dynamoDb
.scan({ TableName, ProjectionExpression: "id" })
.promise();
const apiG = new AWS.ApiGatewayManagementApi({
endpoint: `${domainName}/${stage}`,
});
const postToConnection = async function ({ id }) {
try {
// Send the message to the given client
await apiG
.postToConnection({ ConnectionId: id, Data: messageData })
.promise();
} catch (e) {
if (e.statusCode === 410) {
// Remove stale connections
await dynamoDb.delete({ TableName, Key: { id } }).promise();
}
}
};
// Iterate through all the connections
await Promise.all(connections.Items.map(postToConnection));
return { statusCode: 200, body: "Message sent" };
}