2017-05-15 42 views
0

我正在使用的API以最多50個結果的塊爲單位發送數據。要檢索下一個塊,我需要包含一個偏移量參數,例如。 offset =「50」Firebase中的偏移量node.js https獲取請求循環

請幫我修改我的代碼,包括一個循環,如果在每個循環的結果數= 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(); 

});

+0

是什麼'result'在'result.end' ......這段代碼在所有的工作,它不應該,因爲當'req'不在範圍內時調用'req.end' ** –

回答

0

你可以做到以下幾點,遞歸調用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); 
+0

感謝您的幫助。我已經嘗試了上面的建議,並且腳本沒有結束,在60秒後超時。我試圖將其作爲Firebase功能運行。感謝任何進一步的幫助。 另外我覺得我很混淆res和req變量...... –

+0

'60秒後超時',這好像是一個網絡問題,或者你可能沒有「做任何需要完成的清理工作」 - 我從原始代碼中刪除了'res.end()'和'req.end()',因爲它們不應該在你的代碼中運行 –