Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS API Gateway Web Socket Api - broadcast message to all connected clients

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

like image 270
GCSDC Avatar asked May 02 '19 03:05

GCSDC


People also ask

Does API gateway support WebSocket?

A WebSocket API in API Gateway is a collection of WebSocket routes that are integrated with backend HTTP endpoints, Lambda functions, or other AWS services. You can use API Gateway features to help you with all aspects of the API lifecycle, from creation through monitoring your production APIs.

Can a WebSocket call an API?

You can't call an HTTP API from web socket. You can call a web socket API from a web socket. That mostly means you send some specific message over web socket to the server, and the server sends something specific back.

What type of communication WebSocket APIs allow between clients?

Web Socket APIs allow bi-directional, full-duplex communication between clients and servers. It follows the exclusive pair communication model. This Communication API does not require a new connection to be set up for each message to be sent between clients and servers.


Video Answer


1 Answers

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);
like image 180
Daniel Cottone Avatar answered Sep 18 '22 07:09

Daniel Cottone