When using the Google API Client Library for JavaScript, none of the code samples demonstrate how to get a new token after the previous one has expired. Tokens expire after an hour, so it can't be assumed that the initial token will suffice for every user's stay on your site. The part of the FAQ that deals with refreshing tokens suggests to
refresh the auth token after 45 minutes
Which implies that one should set an interval for 45 minutes and refresh the tokens. The problem with that approach is that when your computer goes to sleep, javascript timers are put on hold, and sometimes take some time to fire after resuming the page. Unfortunately, the first thing your user may want to do when they resume using their computer is to check if there are any updates to your site, and when you make an api call for them, it will fail. So we need to check if our token is still valid before making any calls to the API.
Since I last looked into this problem, I noticed that Google updated the library to return a JavaScript Promise
when you make a call to the library.
var promise = gapi.client.plus.people.search(params);
Because promises are chainable, we can build a pre-check into each API call. I'm using a promise library called Q because I like the syntax better than standard promises, but with a little shuffling this would work with standard promises.
My goal is to be able to make a call like the above without having to wait for it to fail then getting another token then calling the same method again. Instead, I do a precheck. Has the token expired? If not, make the API call. If so, get a token then make the call.