Thursday, 8 June 2017

how to call function in node loop one at a time

this block of code process else block first and then if block, for all request at once, i need a code that execute 5 iterations stop for 15 sec. and then again continue from next 5 iterations and so on.

var http = require("https");
var request = require("request");
var util = require("util");
var async = require("async");
var winston = require("winston");
var wait = require('waitfor');
var moment = require('moment');
var js2xmlparser = require("js2xmlparser");
var dateFormat = require('dateformat');
var db = require("./db");
var settings = require("./settings.js");
var HttpsProxyAgent = require('https-proxy-agent');
var proxy = 'http://asdf.com:80';
var agent = new HttpsProxyAgent(proxy);
var integration = require("./service/integration.service");
var now = new Date();
var reques = [];
var numrequest = [];
var ps = [];
require('waitfor')
var logger = new(winston.Logger)({
transports: [
new(winston.transports.Console)({
    json: false,
    timestamp: true
}),
new(winston.transports.File)({
    filename: 'employeeid1.log',
    json: false
})
]
});


async.waterfall([
function(callback) {
request({
    url: "https://pratik.com/rest/v1/login",
    method: "POST",
    headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Api-Key': 'asdeqwq'
    },
    agent: agent,
    body: '{"credentials":{"username":"' + settings.username + '","company":"' + settings.company + '","password":"' + settings.password + '"}}'
}, function(error, response, body) {

    //    logger.info(myXMLText+" ::: "+JSON.stringify(response));
    //console.log("Inside response:",response);
    var jsonResponse = JSON.stringify(body);
    var jsonResultContent = JSON.parse(body);
    var jsonHeader = JSON.stringify(response)
    var jsonResultHeader = JSON.parse(jsonHeader);
    var _response_code = jsonResultHeader.statusCode;
    var _insertbody = body;
    if (!_insertbody) {
    _insertbody = jsonResponse;
    }
    if (_response_code != 200) {
    console.log("Process is exiting as response code is :" + _response_code);
    process.exit(1);
    }
    console.log("::::::::_response_code::::::: " + _response_code)
    //console.log("_token generated ::: " + jsonResultContent.token);
    //callback(null, jsonResultContent.token)
    callback(null, jsonResultContent.token);
    var abcd = jsonResultContent.token
    //console.log(abcd);
    passotken(abcd);
});
}
]);



function passotken(token, callback) {


async.waterfall([
function(callback) {
db.executesql("select top 20 ext_id as EMPNUM ,  data as datae from newtable", function (data, err) {

    callback(null, data);
    });
},
function(data, callback) {
    var _json_parse = JSON.parse(JSON.stringify(data));
    var rows = data.length;

    console.log(rows)
    var cnt = 1;

    for (var row = 1; row <= rows; row++) {

    logger.info(_json_parse[row-1].EMPNUM);
    //console.log(dateFormat(_json_parse[row].datae));                      
    var req = 'https://pratik.com/ta/rest/v2/companies/|RHV/employees/|' +_json_parse[row-1].EMPNUM + '/timesheets?date=' + dateFormat(_json_parse[row-1].datae, "isoDate");
    //console.log(req);
    var myXMLText = req;

    reques.push(myXMLText);

    }
   // console.log(reques);

    for (var a = 0; a < rows; a++) {

    if(a%5==0)
    {
        console.log("if");
        //console.log(reques[a]);

        //postreq(reques[a],token,sleeped(a));
      /*  setTimeout(function(){sleeped(reques[a],token);;

    },15000); */
        sleeped(reques[a],token);


        //postreq(reques[a],token,sleeped(a));
    }
    else
    {
        console.log("else");
        //console.log(reques[a]);
        //postreq(reques[a],token,sleeped(a));
        postreqELSE(reques[a],token);
    }

    }

Promise.all(ps)
.then((results) => {
console.log("results"); // Result of all resolve as an array
}).catch(err => console.log("err")); 
},
], function(err, result) {
if (!err)
    console.log("Successfully completed")
else console.log(err);
});
};

function callback() {
console.log("completed successfully");
}

function postreq(request1,token)
{
console.log("in 2nd function");



   //console.log( request1 )
    var req_details = request({
        url: request1,
        method: "GET",
        headers: {
        'Content-Type': 'text/xml;charset="UTF-8"',
        'Accept': '**',

        'Authentication':  token
        },

        agent: agent


        // body: myXMLText      
    }, function(error, response, body) {
        var jsonResponse = JSON.stringify(response);
        var jsonResultContent = JSON.parse(jsonResponse);
        var _response_code = jsonResultContent.statusCode;
        //console.log("for employee", + reques[a]);
        var _insertbody = jsonResultContent.body;
        //logger.info("_response_code", +_response_code);

        if (_response_code != 200) {

        if (_response_code == 401) {
            console.log("Authentication is require");
            process.exit();

        }

        if (_response_code == 404) {
            console.log("Employee not found");
            //return;
        }
         if (_response_code == 400) {
            console.log("Missing timesheet profile bad request");
            //return;
        }


        } else {



        var data1 = jsonResultContent.body;
        var data2 = JSON.parse(jsonResultContent.body);





        console.log(jsonResultContent.body);

        var substr = 'action_correct'
        //console.log(body.includes(substr));
        if (!body.includes(substr)) {
            console.log('Already Corrected');
        } else {


            //sleep.sleep(10);


            var abc = JSON.parse(data1).timesheets[0]._links.correct;
            logger.info("abc=" , +abc);
            request({
            url: abc,
            method: "PUT",
            headers: {
                //'Content-Type': 'text/xml;charset="UTF-8"',
                'Accept': '**',
                'Authentication': "bearer " + token
            },

            agent: agent

            }, function(error, response, body) {


            console.log("Inside response");
            //console.log(a, rows);
            var jsonPutResponse = JSON.stringify(response);
            var jsonPutResultContent = JSON.parse(jsonPutResponse);
            var _Putresponse_code = jsonPutResultContent.statusCode;
            console.log(jsonPutResponse);
            var _response_status = (_Putresponse_code == 200) ? "SUCCESS" : (_Putresponse_code == 500) ? "REPROCESS" : "ERROR";
            if (_Putresponse_code == 200) {

                console.log("SUCCESS");
            } else {
                console.log("error");
                if (_Putresponse_code == 401) {
                console.log("token expire");
                if (a == rows) {

                    console.log("exit");
                    process.exit();
                }

                return;

                }
                if (_Putresponse_code == 400) {
                console.log("PayLoad is not valid");
                process.exit();
                }
            }

            function forcallback() {
                console.log("Completed");
                process.exit();
            }
            });
        //}
        }
        if (_response_code == 401) {
            //call token generation function
            console.log(" response was 401")
        }

        function callback() {
            console.log("complerd upper");
            return;

        }

        }

    });
//}

    }

    function sleeped(requesarr,token)
    {
    console.log("in sleeping");
    //console.log(requesarr,token)

    setTimeout(function(){
        postreq(requesarr,token);
    },15000);}


    function postreqELSE(request2,token1)
{
console.log("in 3RD function");

//console.log("from ")

   //console.log(request2 )
    var req_details = request({
        url: request2,
        method: "GET",
        headers: {
        'Content-Type': 'text/xml;charset="UTF-8"',
        'Accept': '**',

        'Authentication': token1
        },

        agent: agent


        // body: myXMLText      
    }, function(error, response, body) {
        var jsonResponse = JSON.stringify(response);
        var jsonResultContent = JSON.parse(jsonResponse);
        var _response_code = jsonResultContent.statusCode;
        //console.log("for employee", + reques[a]);
        var _insertbody = jsonResultContent.body;
        //logger.info("_response_code", +_response_code);

        if (_response_code != 200) {

        if (_response_code == 401) {
            console.log("Authentication is require");
            process.exit();

        }

        if (_response_code == 404) {
            console.log("Employee not found");
            //return;
        }
         if (_response_code == 400) {
            console.log("Missing timesheet profile bad request");
            //return;
        }


        } else {

        //logger.info(jsonResultContent.body)
        //numrequest = jsonResultContent.body;
           // _insertbody = _insertbody.replace(/'/g, "\"").replace(/\r?\n|\r/g, " ");
           // var _insertres = js2xmlparser("response", _insertbody);

        var data1 = jsonResultContent.body;
        var data2 = JSON.parse(jsonResultContent.body);





        console.log(jsonResultContent.body);
    //var numbers = Math.floor(numrequest.length/377);
    //console.log("Above Hi");
        var substr = 'action_correct'
        //console.log(body.includes(substr));
        if (!body.includes(substr)) {
            console.log('Already Corrected');
        } else {


            //sleep.sleep(10);

            //for(nofreq = 0; nofreq < numbers; nofreq++){
            console.log('Present', +body.indexOf(substr));
            var abc = JSON.parse(data1).timesheets[0]._links.correct;
            logger.info("abc=" , +abc);
            request({
            url: abc,
            method: "PUT",
            headers: {
                //'Content-Type': 'text/xml;charset="UTF-8"',
                'Accept': '**',
                'Authentication': "bearer " + token
            },

            agent: agent

            }, function(error, response, body) {


            console.log("Inside response");
            //console.log(a, rows);
            var jsonPutResponse = JSON.stringify(response);
            var jsonPutResultContent = JSON.parse(jsonPutResponse);
            var _Putresponse_code = jsonPutResultContent.statusCode;
            console.log(jsonPutResponse);
            var _response_status = (_Putresponse_code == 200) ? "SUCCESS" : (_Putresponse_code == 500) ? "REPROCESS" : "ERROR";
            if (_Putresponse_code == 200) {

                console.log("SUCCESS");
            } else {
                console.log("error");
                if (_Putresponse_code == 401) {
                console.log("token expire");
                if (a == rows) {

                    console.log("exit");
                    process.exit();
                }

                return;

                }
                if (_Putresponse_code == 400) {
                console.log("PayLoad is not valid");
                process.exit();
                }
            }

            function forcallback() {
                console.log("Completed");
                process.exit();
            }
            });
        //}
        }
        if (_response_code == 401) {
            //call token generation function
            console.log(" response was 401")
        }

        function callback() {
            console.log("complerd upper");
            return;

        }

        }

    });
//}

    }



via pratik mokal

No comments:

Post a Comment