Iterate over an array to iterate a Stitch API function

Hi,

I’m using a working API in Stitch to post stock market information from IEX Cloud in MongoDB.

Below is a working API, but it’s really designed to get information for one stock symbol at a time. When used to process a batch, it’s not ideal.

Does anyone know how I could iterate the function over many stock symbols stored as a value?

Currently, the code will accept batch.symbol: “aapl,fb,googl,tsla”, but this results in one document with one _id and all the stock symbols.

But I really want to iterate through an array and capture data for batch.symbol: [“aapl”, “fb”, “googl”, “tsla”], and create one _id and document for each stock symbol.

exports = function(payload) {
  const httpService = context.services.get('http');
  var batch = context.values.get('batch');

//  Company info
  let url = `https://sandbox.iexapis.com/stable/stock/market/batch?types=company,peers&symbols=${batch.symbol}&token=${batch.token}`;
  
  console.log("Fetching " + url);
  return httpService.get( {url: url}).then(response => {
    
    let json = JSON.parse(response.body.text());
    json.observationDate = new Date(json.dt * 1000);
    
    var collection = context.services.get('mongodb-atlas').db('stocks').collection('profiles');
    collection.insertOne(json);
    console.log('Inserted document!');
  });
};

Thanks!
P

Hi Patrick – Have you tried the following –

  1. Put all tickers in an array
  2. Iterate over the array making one call to IEX per symbol. As a tip, you can simply add the promises to an array without waiting for each to complete.
  3. Once all promises have resolved (you may want to use Promise.all) add the data from the responses to an array and return or insert as separate documents.