Firebase 节点中的偏移量.js https get 请求循环



我正在使用的 API 以最多 50 个结果的块发送数据。要检索下一个块,我需要包含一个偏移参数,例如。偏移量="50"。

请帮我修改我的代码以包含一个循环,如果每个循环中的结果数 = 50,该循环将继续。

提前谢谢你。

 exports.offsetloop = functions.https.onRequest((req,res) => {
    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
            res.end();
            });
        });  
    }
 req.end();

}(;

您可以执行以下操作,递归调用包含大部分代码的 getStuff 函数:

var from = "2017-03-01";
var to = "2017-05-05";
var http = require("https");
function getStuff(offset) {
    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) {
                getStuff(offset + 50);
            } else {
                // all done - do whatever cleanup needs to be done here
            }
        });
    });
}
getStuff(0);

最新更新