google-auth-library 可以批量请求吗?

Can one batch requests with google-auth-library?

到目前为止我使用客户端的方式是这样的

      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);
      });

由于 response 包含消息 ID 列表,我将不得不使用 users.messages.get 来获取每条消息的实际数据。我不希望只为一个查询执行数百个单独的请求。有没有办法批量处理 users.messages.get 请求?

您可以使用 Google API batching requests 功能。这是一个示例函数,它接受消息 ID 数组和客户端作为参数,然后对 users.messages.get 端点执行批处理请求。

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'
  });
};