-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.js
96 lines (88 loc) · 2.25 KB
/
handler.js
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
91
92
93
94
95
96
import * as AWS from "aws-sdk";
module.exports.onConnect = async (event) => {
const connectionId = event.requestContext.connectionId;
const dbClient = new AWS.DynamoDB.DocumentClient();
const putParams = {
TableName: "web-socket-connections",
Item: {
connectionId: connectionId,
},
};
try {
await dbClient.put(putParams).promise();
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify(error),
};
}
return {
statusCode: 200,
};
};
module.exports.onDisconnect = async (event) => {
const connectionId = event.requestContext.connectionId;
const dbClient = new AWS.DynamoDB.DocumentClient();
const delParams = {
TableName: "web-socket-connections",
Key: {
connectionId: connectionId,
},
};
try {
await dbClient.delete(delParams).promise();
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify(error),
};
}
return {
statusCode: 200,
};
};
module.exports.onBroadcast = async (event) => {
let connectionData;
const dbClient = new AWS.DynamoDB.DocumentClient();
try {
connectionData = await dbClient
.scan({
TableName: "web-socket-connections",
ProjectionExpression: "connectionId",
})
.promise();
} catch (e) {
return { statusCode: 500, body: e.stack };
}
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: "2018-11-29",
endpoint:
event.requestContext.domainName + "/" + event.requestContext.stage,
});
const postData = JSON.parse(event.body).data;
const postCalls = connectionData.Items.map(async ({ connectionId }) => {
try {
await apigwManagementApi
.postToConnection({ ConnectionId: connectionId, Data: postData })
.promise();
} catch (e) {
if (e.statusCode === 410) {
console.log(`Found stale connection, deleting ${connectionId}`);
await ddb
.delete({
TableName: "web-socket-connections",
Key: { connectionId },
})
.promise();
} else {
throw e;
}
}
});
try {
await Promise.all(postCalls);
} catch (e) {
return { statusCode: 500, body: e.stack };
}
return { statusCode: 200, body: "Data sent." };
};