Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

node.js - Can one batch requests with google-auth-library?

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?

question from:https://stackoverflow.com/questions/66056908/can-one-batch-requests-with-google-auth-library

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}
Content-Type: application/http

`;
    data += `GET /gmail/v1/users/me/messages/${messageId}`;
    data += '
';
  }
  data += `--${boundary}--`;

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...