14

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)?

Daniel Cottone
  • 4,257
  • 24
  • 39
GCSDC
  • 3,138
  • 3
  • 28
  • 48
  • No way, I think so! You need get all connection ids, then use a loop to send a message to all client. – hoangdv May 02 '19 at 06:28

1 Answers1

14

Unfortunately, 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);
Daniel Cottone
  • 4,257
  • 24
  • 39
  • 5
    Thanks for your answer! I've saw this pattern on many examples, but still hopping to have a way to do that without keeping track of individual ids. – GCSDC May 02 '19 at 14:06
  • 3
    There is a problem with this approach, let's we have 10K clients it means we are calling the AWS api 10k times, which is completely inefficient. To avoid this issue when create your own custom socket server there is an option to create channel, and who ever join the channel they all receive the message at the same time with only one call. I'm wondering if AWS API Gateway also providing this solution. – Dilli Babu Kadati Apr 16 '22 at 14:52
  • 3
    Agreed - It is crazy that in 2022 API Gateway doesn't support the concept of channel broadcasts. So many tech-stacks would switch over to that service if that was addressed. Alternatively you could do something goofy like run half your stack on API Gateway (for 1:1 comms and the other half of your stack on another solution for broadcasts) - this would require multiple WS connections from the client and just makes me so angry. – isaacdre Jul 24 '22 at 18:48