如何在node.js中跨API调用cachingoAuth标记

我已经能够设置我的代码,所以当你向api函数发出请求时,oAuthHandler函数会自动为你处理validation。 我遇到的问题是,我无法find一个方法来caching多个调用的令牌,所以我只请求一个新的令牌,如果它已经过期。

我已经把所有相关的代码文件和我的testing文件的样本放在下面的GIST中。 我只从文件中删除了服务器连接的详细信息。 要点: https : //gist.github.com/jgpeak/56e82c58b368429d4aad

我发现我做错了令牌caching。 我不需要在模块导出之外启动一个variables,而是需要在第一次导出的函数中启动它,以便它绑定到我创build的实例,以便传递给下面更新的其他api方法更新的oAuthHandler。

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