I've created a Web Socket Api using API Gateway and I'm able to connect clients to it.
Also, I'm able to send messages to a connected client by specifying its ConnectionId
and using the following code:
const AWS = require('aws-sdk');
let apiGatewayManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: '/',
region: 'sa-east-1'
});
const params = {
ConnectionId: 'YYYYYYYYYYYYY',
Data: 'test'
};
apiGatewayManagementApi.postToConnection(params, function (err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log(data); // successful response
}
});
The issue is that I don't have the need for differentiating between clients, and so I don't want to keep track of each client's ConnectionId, but if I remove it while sending a message, I get the following error: Missing required key 'ConnectionId' in params
Is there a way to send a message to all connected clients (without specifying any ConnectionId)?
I've created a Web Socket Api using API Gateway and I'm able to connect clients to it.
Also, I'm able to send messages to a connected client by specifying its ConnectionId
and using the following code:
const AWS = require('aws-sdk');
let apiGatewayManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: 'https://XXXXXXXXX.execute-api.sa-east-1.amazonaws.com/dev/',
region: 'sa-east-1'
});
const params = {
ConnectionId: 'YYYYYYYYYYYYY',
Data: 'test'
};
apiGatewayManagementApi.postToConnection(params, function (err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log(data); // successful response
}
});
The issue is that I don't have the need for differentiating between clients, and so I don't want to keep track of each client's ConnectionId, but if I remove it while sending a message, I get the following error: Missing required key 'ConnectionId' in params
Is there a way to send a message to all connected clients (without specifying any ConnectionId)?
Share Improve this question edited May 2, 2019 at 8:33 Daniel Cottone 4,48029 silver badges39 bronze badges asked May 2, 2019 at 3:12 GCSDCGCSDC 3,5004 gold badges30 silver badges50 bronze badges 1- No way, I think so! You need get all connection ids, then use a loop to send a message to all client. – hoangdv Commented May 2, 2019 at 6:28
1 Answer
Reset to default 15Unfortunately, you have to specify the ConnectionId. A pattern that I have seen is to persist connection information to DynamoDB on the $connect
event; then you could do something like this:
const connections = await getAllConnections();
const promises = connections.map(c => apiGwMgmtApi.postToConnection({ ConnectionId: c.connectionId, Data: 'test' }).promise());
await Promise.all(promises);