Can one batch requests with google-auth-library?

190 views Asked by At

The way I have been using the client thus far has been like

      client = new OAuth2Client(
        process.env.GOOGLE_CLIENT_ID,
        process.env.GOOGLE_CLIENT_SECRET,
        "http://localhost:5000/oauth2callback"
      );

      client.setCredentials({refresh_token: getRefreshToken(user)});
      let url = 'https://www.googleapis.com/gmail/v1/users/me/messages?q=myquery';
      client.request({url}).then((response) => {
        doSomethingWith(response);
      });

Since response holds a list of message ids, I will have to use users.messages.get to get the actual data for each message. I would prefer not to do hundreds of separate requests just for one query. Is there a way to batch the users.messages.get requests?

1

There are 1 answers

0
Josh Aguilar On BEST ANSWER

You can use Google APIs batching requests feature. Here's an example function that accepts the array of message IDs and the client as params and then does a batch request to the users.messages.get endpoint.

const batchGetMessages = (messageIds = [], oAuth2Client) => {
  const url = 'https://www.googleapis.com/batch/gmail/v1';
  const boundary = 'message_batch_demo';
  const headers = {
    'Content-Type': `multipart/mixed; boundary=${boundary}`
  };

  let data = '';
  for (const messageId of messageIds) {
    data += `--${boundary}\r\nContent-Type: application/http\r\n\r\n`;
    data += `GET /gmail/v1/users/me/messages/${messageId}`;
    data += '\r\n';
  }
  data += `--${boundary}--`;

  return oAuth2Client.request({
    url,
    headers,
    data,
    method: 'POST'
  });
};