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)?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With