[英]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服务的函数。
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.