Code Monkey home page Code Monkey logo

googleapis-batcher's Introduction

Google Inc. logo

Batching library for Google APIs Node.js Client

Node.js library for batching multiple requests made with the official Google APIs Node.js client

Getting started

First, install the library using yarn/npm/pnpm:

yarn add @jrmdayn/googleapis-batcher

Then instantiate and use the batchFetchImplementation:

import { google } from 'googleapis'
import { batchFetchImplementation } from '@jrmdayn/googleapis-batcher'

const fetchImpl = batchFetchImplementation()

const client = google.calendar({
  version: 'v3',
  fetchImplementation: fetchImpl,
})

// The 3 requests will be batched together
const [list, get, patch] = await Promise.all([
    calendarClient.events.list({ calendarId: '[email protected]' }),
    calendarClient.events.get({
      calendarId: '[email protected]',
      eventId: 'xyz123'
    }),
    calendarClient.events.patch({
      calendarId: '[email protected]',
      eventId: 'xyz456',
      requestBody: { colorId: '1' }
    })
  ])

Options

maxBatchSize

Controls the maximum number of requests to batch together in one HTTP request.

// limit the number of batched requests to 50
const fetchImpl = batchFetchImplementation({ maxBatchSize: 50 })

Note: Google limits the number of batched requests on a per API basis. For example, for the Calendar API it is 50 requests and for the People API it is 1000.

batchWindowMs

Controls the size of the time window (in milliseconds) that will be used to batch requests together. By default, all requests made in the same tick will be batched together. See Dataloader documentation for more on this.

// batch all requests made in a 30ms window
const fetchImpl = batchFetchImplementation({ batchWindowMs: 30 })

signal

Defines a user controlled signal that is used to manually trigger a batch request.

const signal = makeBatchSchedulerSignal();
const fetchImpl = batchFetchImplementation({ signal })

const client = google.calendar({
  version: 'v3',
  fetchImplementation: fetchImpl,
})

const pList = calendarClient.events.list({ calendarId: '[email protected]' }),
const pGet = calendarClient.events.get({
  calendarId: '[email protected]',
  eventId: 'xyz123'
}),
const pPatch = calendarClient.events.patch({
  calendarId: '[email protected]',
  eventId: 'xyz456',
  requestBody: { colorId: '1' }
})

...

signal.schedule();

Known limitations

The max batch size varies per Google API. For example, it is set to 50 for Calendar API and to 1000 for People API. Read the docs to find out and configure the options accordingly.

Batching is homogeneous, so you cannot batch Calendar API and People API requests together. Instead, you must make 2 seperate batching calls, as there are 2 separate batching endpoints. Concretly what it means is that you should always provide a fetchImplementation at the client API level, not at the global Google options level:

const fetchImpl = batchFetchImplementation()

const calendarClient = google.calendar({
  version: 'v3',
  fetchImplementation: fetchImpl,
})

const peopleClient = google.people({
  version: 'v1',
  fetchImplementation: fetchImpl,
})

// This will raise an error
await Promise.all([
    calendarClient.events.list(),
    peopleClient.people.get()
  ])

Do this instead:

const fetchImpl1 = batchFetchImplementation()
const fetchImpl2 = batchFetchImplementation()

const calendarClient = google.calendar({
  version: 'v3',
  fetchImplementation: fetchImpl1,
})

const peopleClient = google.people({
  version: 'v1',
  fetchImplementation: fetchImpl2,
})

await Promise.all([
    calendarClient.events.list(),
    peopleClient.people.get()
  ])

Motivation

On August 12, 2020 Google deprecated its global batching endpoints (blog article here). Going forward, it is recommended to use API specific batch endpoints for batching homogeneous requests together. Unfortunately, the official Google APIs Node.js client does not support batching requests together out of the box. The task of composing a batched request and parsing the batch response is left to the developer.

Here is a link to the official guide for doing so with the Calendar API. As you can see, the task consists in handcrafting a multipart/mixed HTTP request composed of multiple raw HTTP requests (one per request), and then parsing a multipart/mixed response body composed of multiple raw HTTP responses (one per response).

At this point, I see at least 2 reasons as to why developers would not batch Google APIs requests:

  1. There is no easy way to easily generate the individual raw HTTP requests (url + headers + JSON body) from the official Node.js client. The only solution would be to read the developers doc and craft the request by hand..
  2. The task of handcrafting/parsing a multipart/mixed HTTP request/response seems daunting and error prone

Solution

I decided to write this library when I first encountered the need for batching Google APIs requests in Node.js, so that other developers would not have to face the task of writing and parsing multipart/mixed HTTP requests. The key of the solution consists of providing your own fetch implementation to the API client you are using. Google exposes a fetchImplementation parameter in the options (probably for testing purpose) that we can easily override to intercept requests and group them together. For grouping the requests together, we use Dataloader, which can be configured to batch all requests made in one tick, or in a certain time window, or until an external signal is fired.

From a developer's point of vue, you do not need to worry about handcrafting the individual raw HTTP requests. You simply use the official Google APIs Node.js client as normal, and the fetch implementation will automatically batch the requests for you.

googleapis-batcher's People

Contributors

jrmdayn avatar juanmiguelbesada avatar pangolingo avatar snyk-bot avatar tynan-cr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

googleapis-batcher's Issues

THANK YOU!!

Not an issue, just a reminder of how awesome you are!

This package has helped me tremendously

Feel free to close this "issue"

❤️ from Denmark

query params will get escaped accidentally

First of all, thank you for building this amazing tool.

I am trying with some Google API, and I realized if the request path contains query params (e.g. ?format=metadata), it will get escaped by the Handlebars template at this line

which will result in a request failure.

My temporary fix is changing {{path}} to {{{path}}}, but I am not an expert of Handlebars, so not sure if this has any side effect, but this change did fix my issue.

Getting an "Missing end time." error

Hey, thanks for making this useful package. I just wanted to let you know that I'm trying to use it and hitting this error:

  errors: [
    {
      domain: 'global',
      reason: 'required',
      message: 'Missing end time.'
    }
  ]

I tried erasing my node modules and package-lock, then reinstalling everything, and I still got this error. I only get it when trying to insert multiple calendar events in a batch. When I try to insert a single event it works fine.

If you have any ideas about what's going on here that'd be great. I've checked the data format and despite the error, the "end time" is provided and is in the valid format.

Set a license on this project.

The official client uses the Apache 2.0 license. Use the same one or any other license that fits on this one too please.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.