0

I have a lambda function that returns a message to the client.

function replyToMessage (messageText,connectionId) {
     const data = {message:messageText}
     const params = {
         ConnectionId : connectionId,
         Data: Buffer.from(JSON.stringify(data))
     }
     return api.postToConnection(params).promise()
         .then(data => {})
         .catch(error => {console.log("error",error)})
}

This code is called once when the connection is made and I get a response to my client. When I call the function again with a different endpoint, it doesn't send a response to my client. However, when I call it a third time, I get the response to my client from the second call. Here's my switch when the Lambda function is called.

switch(route) {
    case "$connect":
        break
    case "$disconnect":
        break
    case "connectTo":
        await connectToService(JSON.parse(event.body).eventId,connectionId)
        await replyToMessage("Connected eventId to connId",connectionId)
        break
    case "disconnectFrom":
        await disConnectToService(JSON.parse(event.body).eventId,connectionId)
        break
    case "project":
        responseItems = await getBroadcastIds (JSON.parse(event.body).eventId,JSON.parse(event.body).sourceId,connectionId)
        console.log(responseItems)
        responseItems.Items.forEach(async function(item) {
            await replyToMessage(JSON.parse(event.body).sourceId,item.connectionId)
        })
        responseItems = []
        break
    default :
        console.log("Unknown route", route)
M Charles
  • 165
  • 1
  • 1
  • 14

1 Answers1

0

The issue appears to be the async forEach loop. Switching to the following resolves the issue.

for (const item of responseItems.Items) {
   console.log("Sending to:",item.connectionId);
   await replyToMessage(JSON.parse(event.body).sourceId,item.connectionId)
}

See this post for the answer that led to this resolution. Using async/await with a forEach loop

M Charles
  • 165
  • 1
  • 1
  • 14