Bhavesh Daswani
Bhavesh Daswani

Reputation: 725

Pubnub function xhr module is calling server endpoint multiple times ( it should call only one time )

I have been using pubnub for realtime communication between mobile devices. The scenario I am creating is as follows:

  1. The sender mobile device will publish a message to pubnub.
  2. The message will call a On Before Function PubNub Function where original message is sent to laravel endpoint where it is persisted and the database record id is added to the message and published to the subscriber.

(Laravel endpoint is called using xhr module from PN Function)

The issue I am facing is that my laravel endpoint is called approximately 7 to 12 times for each publish the message.

Below is my onBefore PubNub function.

export default (request) => { 
    console.log('intial message: ',request.message);
    const kvstore = require('kvstore');
    const xhr = require('xhr');
    const http_options = {
        "timeout": 5000, // 5 second timeout.
        "method": "POST",
        "body": "foo=bar&baz=faz"
    };

    const url = "redacted_backend_url";

    return xhr.fetch(url,http_options).then((x) => {
        console.log('Messages after calling ajax: ',request.message.content);
        // here i am changing the message
        request.message.content = 'hello world'; 
        return request.ok();
    }).catch(err=>console.log(err)) ;
}

Please identify what exactly wrong.

Upvotes: 1

Views: 125

Answers (1)

Craig Conover
Craig Conover

Reputation: 4738

PubNub Function Wildcard Channel Binding

Your Function is bound to channel '*' which of course means capture all publishes to all channels. What you don't know is that console.log in a Function publishes the message to a channel that looks like this: blocks-output-kpElEbxa9VOgYMJQ.77042688368579w9

And the Functions output window is subscribed to that channel to display your console.log's. So when the Function is invoked, it publishes a message to the console.logs channel which is captured by your Function, which calls console.log and eventually, a configured recursion limit is hit to protect you from getting into an infinite loop.

So if you were to change your channel binding to something like foo.* and publish to a channel like foo.bar, this undesired recursion would be avoided. In production, the console.logs should be removed, too, and it would not cause this to happen.

Additionally, you could implement some channel filter condition at the top of the your Function to prevent it from further execution your Function code:

if (channel.startsWith("blocks-output"))
    return request.ok()
}

Upvotes: 1

Related Questions