Monday, 15 May 2017

Offsets in a node.js https get request loop

The API I am working with sends data in blocks of 50 results maximum. To retrieve the next block I need to include an offset parameter eg. offset="50".

Please help me amend my code to include a loop that will continue if the number of results in each loop = 50.

Thank you in advance.

 exports.offsetloop = functions.https.onRequest((req,result) => {

    var offset = "0";
    var from = "2017-03-01";
    var to = "2017-05-05";

    var http = require("https");
    var options = {
        "method": "GET",
        "hostname": "example.com",
        "port": null,
        "path": "/api/v1/entries.json?to="+to+"%2B00%253A00%253A00&from="+from+"%2B00%253A00%253A00&offset="+offset+"&api_key=123456",
        "headers": {
            "accept": "application/json"
        }
    };

    var req = http.request(options, function (res) {
        var chunks = [];

        res.on("data", function (chunk) {
            chunks.push(chunk);
        });

        res.on("end", function () {
            var body = Buffer.concat(chunks).toString();

            body = JSON.parse(body);
            //save to database etc.
            //if(body.length == 50) loop using offset = 50

            result.end();
            });

        });  
    }
 req.end();

});



via Thomas Headland

No comments:

Post a Comment