External API Request

Hi Guys… not sure if it is a problem with backendless or my code, however, the code works sometimes so not sure what is going on… any help would be most appreciated.

My code follows… as you can see I have tried three different approaches to get this simple POST API call to work, but I cannot get it to work consistently.

/**
* Timer timer.
* It is executed according to the schedule
*/
Backendless.ServerCode.addTimer({

  name: 'Timer',

  startDate: 1552460305191,

  frequency: {
    schedule: 'custom',

    repeat: {'every':5}
  },

  /**
  * @param {Object} req
  * @param {String} req.context Application Version Id
  */
  execute(req){
    //add your code here


    //var successHandlerTrades = function( response ) {  
    //console.log("Trade Sent to ProveSource!");
    //};  

    //var errorHandlerTrades = function( response ) {  
    //console.log("Trade Error!");
    //};

    var logger = Backendless.Logging.getLogger('SERVER_CODE');
    
    var trade = Math.floor((Math.random() * 4) + 1);
    
    //1 in 4 chance
    if (trade == 1){
        //update trade table
        Backendless.Counters.getAndIncrement( "Trades" ).then( tradeSuccessCallback ).catch( tradeFailureCallback );
        //Backendless.Logging.getLogger("SERVER_CODE").info("Trade DB Updated!");
        console.log("Trade DB Updated!");
  

        const https = require('https');

        return new Promise((resolve, reject) => {
            https.request('https://api.provesrc.com/webhooks/track/004045010554b3db2e4d7028deb0ff48', (res) => {
            
            console.log(`statusCode: ${res.statusCode}`);
            
            
            let body = '{email:"tradecounter@beaxchange.com"}';

            res.on('data', (chunk) => body += chunk);
            res.on('end', () => {
                req.item.apiCallResult = body;

                resolve();
            });

            res.resume();
            }).on('error', reject);
        });


        //Provesource record trade
        //Backendless.Request.verbose = true;
        //Backendless.Request['post']('https://api.provesrc.com/webhooks/track/004045010554b3db2e4d7028deb0ff48').send({email:"tradecounter@beaxchange.com"})
        //.then(result => console.log('Result, Trade to ProveSource: '+result))
        //.catch(error => console.error('Error, Trade Not Sent to ProveSource Successfully: '+error))
        
        //Backendless.Events.dispatch( "ProveSourceTradesUpdate", "")
        //.then( successHandlerTrades )  
        //.catch( errorHandlerTrades );
      
    }
     
  }
});

Hello Gary,

Please provide more information. What do you mean by works sometimes? Is it random?

Also, please add more logs in your code so it would be easier to verify when your code fails.
E.g.

execute(req) {
   // log here after execution started
}

Regards,
Olga

Thank you for your response Olga. I can tell when the API call works as it is logged as an event via the external providers website (Provesource). Please see the screenshot attached.

However, this timer is triggered every 5 seconds in Backendless and should send the API call close to 25% of the time (due to my randomisation code…

var trade = Math.floor((Math.random() * 4) + 1);
    
    //1 in 4 chance
    if (trade == 1){
    ....

You can also see that the log is running the code correctly. Please see second screenshot below.

You will notice the “Trade DB Updated!” message inside the log… This tells me the API call should have been fired off to ProveSource

1 Like

Hello Gary
I can recommend you to replace https.request with our Backendless.Request it’s already loaded inside Business Logic

before:

return new Promise((resolve, reject) => {
            https.request('https://api.provesrc.com/webhooks/track/004045010554b3db2e4d7028deb0ff48', (res) => {
        
        console.log(`statusCode: ${res.statusCode}`);
        
        
        let body = '{email:"tradecounter@beaxchange.com"}';

        res.on('data', (chunk) => body += chunk);
        res.on('end', () => {
            req.item.apiCallResult = body;

            resolve();
        });

        res.resume();
        }).on('error', reject);
    });

after:

 return Backendless.Request.post('https://api.provesrc.com/webhooks/track/004045010554b3db2e4d7028deb0ff48', {email:"tradecounter@beaxchange.com"})

Regards, Vlad

Thank you Vlad… That worked perfectly… and cleaned up my code also :smiley: