MrCrowly
MrCrowly

Reputation: 168

How can I cache oAuth token across API calls in node.js

I have been able to set my code up so that when you make a request to an api function an oAuthHandler function automatically handles authentication for you. The problem I am having though is that I can't find a way to cache the token across multiple calls so I only request a new token if it has expired already.

I have put samples of all the relevant code files and my test file in the following GIST. I have only removed the server connection details from the file. Gist: https://gist.github.com/jgpeak/56e82c58b368429d4aad

Upvotes: 2

Views: 5983

Answers (1)

MrCrowly
MrCrowly

Reputation: 168

I found what I did wrong with the token caching. Instead of initiating a variable outside the module export I needed to initiate it within the function of the first export so that it binds to the instance I create to pass to the other api methods updated oAuthHandler below.

(function() {
'use strict';

//Required Modules
// ===============
const request = require('./requestHandler');
const cache = require('memory-cache');

//Hidden Variables
// ===============

module.exports = (oAuth) => {
  var cachedToken = null;
  return (processor, options, postData) => new Promise(function (resolve, reject) {

    var errorProcessor = (err) => {
      //If authorization failure refresh token and try one more time
      if(err.statusCode && err.statusCode === 401){
        return oAuth.getToken()
          .then((token)=>{
            cachedToken = token;
            return request(token, processor, options, postData);
          })
          .then((response) => resolve(response))
          .catch((err) => {
            reject(err);
          });
      }
      return reject(err);
    };

    if(cachedToken){
      return request(cachedToken, processor, options, postData)
        .then((response) => resolve(response))
        .catch(errorProcessor);
    }
    else {
      return oAuth.getToken()
        .then((token)=>{
          cachedToken = token;
          return request(token, processor, options, postData);
        })
        .then((response) => resolve(response))
        .catch(errorProcessor);
    }
  });
};

}());

Upvotes: 1

Related Questions