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