[英]How to set up Relay Modern with a Promise-based Environment? (e.g. Auth0 or another async authentication service?)
In Relay Classic, we would just pass a function to react-relay-network-layer to return the required token in a promise. 在Relay Classic中,我们只需将一个函数传递给react-relay-network-layer即可在promise中返回所需的令牌。 What's the equivalent in Relay Modern?
什么是中继现代?
Ideally I'd like to display the Loading screen until the Environment promise resolves, and then display the main Component once we have an Environment and the query is fetched. 理想情况下,我想显示“正在加载”屏幕,直到“环境”承诺解决为止,然后在有了“环境”并提取查询后显示主组件。
So if I knew how to swap out QueryRenderer's environment, that would also solve the issue. 因此,如果我知道如何换出QueryRenderer的环境,那也将解决问题。
The recommended method here is to fetch the authentication token inside of fetchQuery. 推荐的方法是在fetchQuery内部获取身份验证令牌。
The remaining challenge is how to make sure the async authentication function is called only once, even if Relay fetches multiple times while authentication is still ongoing. 剩下的挑战是如何确保异步身份验证功能仅被调用一次,即使中继在身份验证仍在进行中多次提取时也是如此。 We did this using a singleton promise;
我们使用单身的承诺来做到这一点; each call to fetchQuery calls the static Promise.resolve() method on the same promise, so that once the authentication call finishes, all fetchQuery calls continue with the desired authentication information.
每次对fetchQuery的调用都在相同的promise上调用静态Promise.resolve()方法,因此,一旦身份验证调用完成,所有fetchQuery调用便会继续提供所需的身份验证信息。
So fetchQuery
gets an auth token (JWT) with: 因此,
fetchQuery
获得具有以下内容的身份验证令牌(JWT):
const authToken = await AuthToken.get();
And AuthToken looks like (TypeScript): AuthToken看起来像(TypeScript):
class AuthToken {
private static _accessTokenPromise: Promise<string>;
public static async get() {
if (!this._accessTokenPromise)
this._accessTokenPromise = this.AuthFunction(); // AuthFunction returns a promise
return await Promise.resolve(this._accessTokenPromise);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.