WHOATEMYNOODLES
WHOATEMYNOODLES

Reputation: 897

API Gateway websockets - Function is sending two messages

I'm using the serverless apigateway websockets and I can successfully get messages sent back and forth between the lambda function and client.

However I can't figure out how to get my function to send only a single message. It's currently sending two messages due to the callback at the end of the function. This is more of a nodejs issue, but I've been trying for the past couple of hours to figure out how, but can't seem to.

 var params2 = {
        TableName: "UserConnections",
        FilterExpression: "cameraId = :val",
        ExpressionAttributeValues: { ":val": {"S" : JSON.parse(event.body).data.camera_id}}
    };


    DDB.scan(params2, function(err, data) {
       if (err) throw err; 
       console.log("DATA: " + JSON.stringify(data));

       for(var i = 0; i<data['Items'].length; i++){
           var id = data['Items'][i]['connectionId'].S;
           console.log("List of connection ids: " + id);


            var params3 = {
              ConnectionId: id,
              Data: JSON.stringify(message)
            };

            apigatewaymanagementapi.postToConnection(params3, function(err, data) {
              if (err){
                  throw err; // an error occurred
              }else{
                  console.log("Success sending message to clients: " + JSON.stringify(data)); 
              }
            }); 
       }
    });



    callback(null, {
         statusCode: 200,
         body: "Message Processed in Lambda!"
    });

In postToConnection method, it sends a message back to multiple users, and the callback function sends the body to the same users. How can I just send the params3 back to the users and not use the callback to end the function

Edit1:______________________________________________

enter image description here

Adding

 callback(null, {});

Still sends two messages except the second one is now empty. How can I get it to strictly send only one message

Upvotes: 0

Views: 1036

Answers (1)

hoangdv
hoangdv

Reputation: 16147

Return with a empty object, the return value is ignored when this function is invoked from WebSocket gateway

    return {}; // callback(null, {});

Upvotes: 1

Related Questions