Pascal Schott
Pascal Schott

Reputation: 61

AWS Websocket API

I am using the API Gateway Websocket.

When I send a message to the client from a Lambda function, it sometimes doesn't send a message and other times it sends 2-3 messages.

const AWS = require("aws-sdk")

const api = new AWS.ApiGatewayManagementApi({
    endpoint : process.env.API_ENDPOINT
})

exports.handler = async (event) => {
    console.log(event)
    const body = JSON.parse(event.body)
    const connectionId = event.requestContext.connectionId

    sendMessage(connectionId, "My Message")

    return {}
};

const sendMessage = (connectionId, response) => {
    const data = { message : response }

    const params = {
         ConnectionId : connectionId,
         Data : Buffer.from(JSON.stringify(data))
    }

    return api.postToConnection(params).promise()
}

Upvotes: 0

Views: 392

Answers (1)

Pascal Schott
Pascal Schott

Reputation: 61

Actually i had to await the sendMessage function. This solved my problem.

Upvotes: 1

Related Questions