How to build real-time applications using WebSockets with AWS API Gateway and Lambda

Janitha Tennakoon
Feb 6 · 10 min read

WebSocket API Concepts

POST https://{api-id}.execute-api.us-east 1.amazonaws.com/{stage}/@connections/{connection_id}

Implementing chat application

Creating WebSocket API

exports.handler = (event, context, callback) => {
const connectionId = event.requestContext.connectionId;
addConnectionId(connectionId).then(() => {
callback(null, {
statusCode: 200,
})
});
}
function addConnectionId(connectionId) {
return ddb.put({
TableName: 'Chat',
Item: {
connectionid : connectionId
},
}).promise();
}
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();
exports.handler = (event, context, callback) => {
const connectionId = event.requestContext.connectionId;
addConnectionId(connectionId).then(() => {
callback(null, {
statusCode: 200,
})
});
}
function addConnectionId(connectionId) {
return ddb.delete({
TableName: 'Chat',
Key: {
connectionid : connectionId,
},
}).promise();
}
wscat -c wss://bh5a9s7j1e.execute-api.us-east-1.amazonaws.com/Test
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();
require('./patch.js');
let send = undefined;
function init(event) {
console.log(event)

const apigwManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: event.requestContext.domainName + '/' + event.requestContext.stage
});



send = async (connectionId, data) => {
await apigwManagementApi.postToConnection({ ConnectionId: connectionId, Data: `Echo: ${data}` }).promise();
}
}
exports.handler = (event, context, callback) => {
init(event);
let message = JSON.parse(event.body).message
getConnections().then((data) => {
console.log(data.Items);
data.Items.forEach(function(connection) {
console.log("Connection " +connection.connectionid)
send(connection.connectionid, message);
});
});

return {}
};
function getConnections(){
return ddb.scan({
TableName: 'Chat',
}).promise();
}
require('aws-sdk/lib/node_loader');
var AWS = require('aws-sdk/lib/core');
var Service = AWS.Service;
var apiLoader = AWS.apiLoader;
apiLoader.services['apigatewaymanagementapi'] = {};
AWS.ApiGatewayManagementApi = Service.defineService('apigatewaymanagementapi', ['2018-11-29']);
Object.defineProperty(apiLoader.services['apigatewaymanagementapi'], '2018-11-29', {
get: function get() {
var model = {
"metadata": {
"apiVersion": "2018-11-29",
"endpointPrefix": "execute-api",
"signingName": "execute-api",
"serviceFullName": "AmazonApiGatewayManagementApi",
"serviceId": "ApiGatewayManagementApi",
"protocol": "rest-json",
"jsonVersion": "1.1",
"uid": "apigatewaymanagementapi-2018-11-29",
"signatureVersion": "v4"
},
"operations": {
"PostToConnection": {
"http": {
"requestUri": "/@connections/{connectionId}",
"responseCode": 200
},
"input": {
"type": "structure",
"members": {
"Data": {
"type": "blob"
},
"ConnectionId": {
"location": "uri",
"locationName": "connectionId"
}
},
"required": [
"ConnectionId",
"Data"
],
"payload": "Data"
}
}
},
"shapes": {}
}
model.paginators = {
"pagination": {}
}
return model;
},
enumerable: true,
configurable: true
});
module.exports = AWS.ApiGatewayManagementApi;
{"action" : "onMessage" , "message" : "Hello everyone"}

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead

Janitha Tennakoon

Written by

Senior Software Engineer at 99X Technology, Sri Lanka

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead