Websocket

AWS serverless documentation

Authorization

Using API Gateway blog

Iam Role

Events handled by CreateSocket labmda:

  • Connect
      • Do Not Message the client from the $connect route. If you do this, it’ll give you an error. This is because the connection is not established yet at that point.  Use callback instead.
      • We need the “connectionId ”to send a message back to the client. “domainName” and “stage” is needed for this purpose as well since the URL has to be formatted in a specific way. Of course we can use the HTTP Url without creating the URL from the “domainName” and “stage”, but then the main purpose of using a serverless approach is omitted.
  • Disconnect
  • Default
    • Sending a message back to client will happen here
"use strict";
const AWS = require("aws-sdk");

module.exports.handler = (event, context, callback) => {
  createSocket(event, callback);
};

const createSocket = async (event, callback) => {
  try {
    if (event.requestContext) {
      const { connectionId, routeKey, domainName, stage } =
        event.requestContext;

      switch (routeKey) {
        case "$connect":
          break;

        case "$disconnect":
          break;

        default:
          const callbackUrlForAWS = `https://${domainName}/${stage}`;
          sendMessageToClient(callbackUrlForAWS, connectionId, {
            connectionId: connectionId,
            callbackUrlForAWS: callbackUrlForAWS,
          });
          break;
      }
    }

    callback(null, {
      statusCode: 200,
    });
  } catch (error) {
    console.log("ERROR==>", error);
    callback(null, {
      statusCode: 500,
    });
  }
};

const sendMessageToClient = (url, connectionId, payload) =>
  new Promise((resolve, reject) => {
    const apiGatewayManagementApi = new AWS.ApiGatewayManagementApi({
      apiVersion: "2018-11-29",
      endpoint: url,
    });
    apiGatewayManagementApi.postToConnection(
      {
        ConnectionId: connectionId,
        Data: JSON.stringify(payload),
      },
      (err, data) => {
        if (err) {
          console.log("sendMessageToClient ERROR==>", err);
          reject(err);
        }
        resolve(data);
      }
    );
  });

React Front End

Asynchronous Client Interaction in AWS Serverless (good graphes comparing all approaches)