mmm111mmm
mmm111mmm

Reputation: 4085

Get Gmail thread subjects (in a sane way)

I'm trying to use the Gmail API to retrieve all the thread subjects in a gmail account.

That's easy with threads.list, but that mainly gets the ID of the thread, not the subject.

The only way I've found is by using threads.list then, for each thread, calling threads.get and fetching the subject from the headers in the payload metadata.

Obviously this makes a lot of API calls, i.e. 101 calls if there's 100 threads.

Is there a better way?

Here's the code I'm currently using:

var getIndivThread = function(threads) {
  threads.threads.forEach(function(e) {
    indivThreadRequst.id = e.id, 
    gmail.api.users.threads.get(indivThreadRequst).execute(showThread);
  });
};
var indivThreadRequst= {
    format: 'metadata',
    metadataHeaders:['subject'], 
    userId: myUserId, 
    maxResults:1};
var showThread = function(thread) {
  console.log(thread.messages[0].payload.headers[0].value);
};
gmail.api.users.threads.list({userId:myUserId}).execute(getIndivThread);

Upvotes: 4

Views: 1403

Answers (1)

rrowland
rrowland

Reputation: 2814

Unfortunately, there isn't a way to get more than one thread subject at a time through the current API. However, there are a few things you might do to improve the performance:

  1. Use the API's paging feature to fetch limited amounts of threads at once.

  2. Fetch batches of messages in parallel rather than attempting to fetch all at once or one at a time. Experiment for yourself, but 5 would be a good number to start with.

  3. If this is a browser implementation, consider making a call to your back-end instead of making the calls from the browser. This way the client only makes 1 call per page, and it allows you to potentially add caching and pre-loading mechanisms to your server that will improve the customer experience. The potential downside here is scalability; as you get more clients, you'll need considerably more processing power than an fat-client approach.

As an example of #2, you could fetch 5 initially, and then have the callback for each function fire the next call so there are always 5 fetching concurrently:

var CONCURRENCY_LIMIT = 5;

function getThread(threadId, done) {
  threadRequest.id = e.id;
  gmail.api.users.threads.get(threadRequest).execute(function(thread) {
    showThread();
    done();
  });
}

gmail.api.users.threads.list({userId:myUserId}).execute(function(threads) { 
  function fetchNextThread() {
    var nextThread = threads.shift();
    nextThread.id && getThread(nextThread.id, fetchNextThread);
  }

  for (var i = 0; i < CONCURRENCY_LIMIT; i++) {
    fetchNextThread();
  }
});

Upvotes: 3

Related Questions