【问题标题】:How can I cache oAuth token across API calls in node.js如何在 node.js 中跨 API 调用缓存 oAuth 令牌
【发布时间】:2016-06-23 04:43:28
【问题描述】:

我已经能够设置我的代码,以便当您向 api 函数发出请求时,oAuthHandler 函数会自动为您处理身份验证。我遇到的问题是我找不到在多个调用中缓存令牌的方法,所以我只在它已经过期时才请求新令牌。

我已将所有相关代码文件的示例和我的测试文件放在以下 GIST 中。我只从文件中删除了服务器连接详细信息。 要点:https://gist.github.com/jgpeak/56e82c58b368429d4aad

【问题讨论】:

    标签: node.js node-rest-client


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-08
      • 2013-08-11
      • 2018-05-12
      • 2015-07-01
      • 2020-06-08
      • 2018-05-07
      • 1970-01-01
      • 2016-03-21
      相关资源
      最近更新 更多