I'm trying to batch fetch from the iexcloud api, a string of 100 symbols at a time, using firebase functions. My first fetch responds and writes to the DB correctly. On my second call I constantly get "Client network socket disconnected before secure TLS connection was established " .. not sure what I'm doing wrong here:
const functions = require("firebase-functions");
const fetch = require("node-fetch");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
exports.scheduledFunctionCrontab = functions.pubsub
.schedule("0 09-17 * * 1-5")
.timeZone("America/New_York") // Users can choose timezone - default is America/Los_Angeles
.onRun(async () => {
const promises = [];
const positions = await admin.firestore().collection("positions");
const tempDoc = [];
await positions.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
tempDoc.push(doc.id);
});
return tempDoc;
});
// Let's break this into groups of 100.
let positionsObject = tempDoc.reduce((resultArray, item, index) => {
let perChunk = 100; // items per chunk
const chunkIndex = Math.floor(index / perChunk);
if (!resultArray[chunkIndex]) {
resultArray[chunkIndex] = []; // start a new chunk
}
resultArray[chunkIndex].push(item);
return resultArray;
}, []);
async function databaseWrite(json) {
...
// writing to the DB
...
}
async function getCurrentPrice() {
for (const symbols of positionsObject) {
let ourPositionsString = symbols.toString();
const API_Call = `https://sandbox.iexapis.com/stable/stock/market/batch?symbols=${ourPositionsString}&types=quote&token=TOKEN`;
const fetchResponse = await fetch(API_Call, {
method: "GET",
agent: false,
});
const json = await fetchResponse.json();
await databaseWrite(json);
}
}
getCurrentPrice();
return Promise.all(promises);
});
databaseWrite works, and the API_Call loops successfully with a new ourPostitionsString of the correct 100 positions, but the 2nd fetch response is always socket disconneceted..