简体   繁体   English

如何使用静态方法将身份验证令牌传递给API类

[英]How can I use static methods to pass auth tokens to an API class

I wrote an API class that I use with redux saga to separate the actual network calls from the sagas, and that class looks somewhat like this: 我编写了一个与redux saga一起使用的API class ,以将实际的网络调用与sagas分开,该类看起来像这样:

    export default class ApiService {

        constructor(bearer) {
            this.instance = axios.create({
                ...
                headers: {
                    'Authorization': `Bearer ${bearer}`
                }
            })
        }

        fetchPosts = async () => {
            const response = this.instance.get(.....)
        }
        ........
    }

However in my sagas I have to instantiate a new object every time within a saga like this: 但是,在我的Sagas中,每次必须在像这样的传奇中实例化一个新对象:

    const { accessToken } = yield select(getAuth)
    const apiService = new ApiService(accessToken);

Is there a better approach I could take with this so I can remove those 2 lines of code from every saga call and still make sure that the object will have the correct bearer token? 有什么更好的方法可以解决,以便可以从每个saga调用中删除这两行代码,并仍然确保对象具有正确的承载令牌?

Thanks? 谢谢?

replace your bearer with a class variable: 用类变量替换您的载体:

export default class ApiService {

  constructor(bearer) {

    this.instance = axios.create({
      ...
      headers: {
        'Authorization': `Bearer ${ApiService.bearer}`
      }
    })
  }

  fetchPosts = async () => {
    const response = this.instance.get(.....)
  }
  ........
}

and somewhere just initialise it one time before you use it like this: 在某处只需初始化一次,然后再使用,就像这样:

ApiService.bearer = "my bearer";

Try creating a function which returns new api service only if it's the first call or the token is updated. 尝试创建一个仅在首次调用或令牌已更新时才返回新api服务的函数。

api.js api.js

let api;
let token;

const isNewToken = (newToken) => newToken !== token;
const getApi = (newToken) => {
  const isTokenUpdated = newToken !== token;
  const shouldCreateService = !api || isTokenUpdated;

  if (shouldCreateService) {
    api = new ApiService(newToken);
  }

  return api;
}

export { getApi }; 

Then create some helper generators 然后创建一些辅助生成器

function* retrieveToken() {
  return yield select(getAuth);
}

function* resolveApi() {
  const token = yield retrieveToken();
  return getApi(token); // getApi from api.js
}

Then in your main sagas you can use it like this: 然后在您的主Sagas中可以像这样使用它:

function* fetchPostsSaga() {
  const api = yield resolveApi();
  // Rest of code using api
  ...
}

Since the authorization token is stored in the Redux State the creation of the ApiService is bound to Redux lifecycle. 由于授权令牌存储在Redux状态中,因此ApiService的创建将绑定到Redux生命周期。 If possible I would move retrieval of a token outside of Redux . 如果可能的话,我会将检索令牌的工作移到Redux之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用多个 npm 身份验证令牌 - How to use multiple npm auth tokens 如何导出静态类方法而不导出整个类 - How can I export static class methods without exporting the whole class 我什么时候想在 JavaScript 中使用“类”(静态)方法或属性? - When would I want to use “class” (static) methods or properties in JavaScript? 如何创建可以调用多个对象/上下文的非静态方法/类? - How to create non-static methods/class that I can call off of multiple objects/contexts? 我可以使用EmberJS mixins添加(静态)类方法 - Can I add (static) class methods using EmberJS mixins 如何在javascript中传递方法? - How can I pass methods in javascript? 我们如何在javascript类方法中传递参数 - How can we pass parameters in javascript class methods 如何使用来自 class 的 static getter 并调用 object 并使用 this 关键字? - How can I use a static getter from a class and call an object and use the this keyword? 如何将身份验证标头传递给其他组件 - How can I pass auth headers to other components 如何将类名作为 arguments 传递并在 GWT jsni 中调用常见的 static 方法? - How to pass class-name as arguments and invoke common static methods in GWT jsni?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM