Batch

Batch

An object that represents a collection of requests that will be asynchronously retrieved. Use add to add request objects, and then fetchAll which interacts with APIs concurrently and return them all. The responses will be in the same order as the requests.

You can also iterate over this object with for … of syntax, and it does so by chunking the requests, passing back time to the caller to process.

Constructor

new Batch(rateLimitopt, lastExecutionDateopt, verboseopt) → {Batch}

Usually created with call to Endpoints.batch

Parameters:
Name Type Attributes Default Description
rateLimit Number <optional>
50

The maximum number, per second, that the endpoint can take before raising 429. error. (This often applies per IP address)

lastExecutionDate Date <optional>
null

Uses this as basis for understanding how much longer it has for a second to elapse. In most cases, safest to leave as null

verbose Boolean <optional>
false

set to true if you want to see messages indicating when it's sleeping in order to ensure the rate limit isn't exceeded

Source:
Example
// create the object
const batch = Endpoints.batch();

// add request objects
batch.add({request});  // Request

// use `fetchAll` to grab them all at once
const responses = batch.fetchAll();

// get the json
const response = responses[0];
Logger.log(response.json);

// or
// iterate over the object and get one at a time
for (const response of batch) {
  Logger.logger(response.json);
}

Methods

add(request)

Add request to batch queue

Parameters:
Name Type Description
request Request

An Endpoints.Request object

Source:

fetchAll() → {Array.<Response>}

Use UrlFetchApp to reach out to the internet. Returns Response objects in same order as requests. You need to use json property to get the data result. Note that Response objects also have request property, which can be used to debug, or rebuild the original request, if necessary. Any mixin classes that are used on request creation will be available on the response object.

Handles 429 errors smartly. Instead of trying again with all of the requests, its subsequent attempt will only fetch those that had 429. Note that the current algorithm assumes these batch requests are going to the same endpoint. TODO: better algorithm not assuming same endpoint

Source:
Examples
// Make list of response jsons
batch.fetchAll().map(response => response.json);
// Make list of original request urls
batch.fetchAll().map(response => response.request.url);
// request with mixins
const req = Endpoints.createRequest('get', {}, {
  param: 1
});
const batch = Endpoints.batch();
batch.add({request: req});
const responses = batch.fetchAll();
const response = responses[0];
Logger.log(response.param);  // 1