我在 React-Native 应用程序中使用 Apollo(带有 Graph Cool)、redux 和 Auth0。我试图延迟查询和突变,直到设置标题。
idToken 存储在异步存储中,因此是一个承诺。我不能使用 redux 来传递令牌,因为这会产生循环依赖。
当用户第一次登录或令牌已过期时,在设置标头之前发送查询,这意味着我收到错误Error: GraphQL error: Insufficient Permissions
如何延迟查询,直到找到令牌并将其添加到标头?我一直在寻找三个主要的解决方案:
- 添加 forceFetch: true; 这似乎是 Apollo 客户端早期实现的一部分。即使我找到了等价物,该应用程序在第一次尝试获取时仍然失败。
- 登录时重置商店(补水?)。这仍然是异步的,所以我看不出这会如何影响结果。
- 从登录本身中删除所有突变和查询,但是由于应用程序的进度,这是不可行的。
一些片段:
const token = AsyncStorage.getItem('token');
const networkInterface = createNetworkInterface({ uri:XXXX})
//adds the token in the header
networkInterface.use([{
applyMiddleware(req, next) {
if(!req.options.headers) {
req.options.headers = {}
}
if(token) {
token
.then(myToken => {
req.options.headers.authorization = `Bearer ${myToken}`;
})
.catch(err => console.log(err));
}
next(); // middleware so needs to allow the endpoint functions to run;
},
}]);
// create the apollo client;
const client = new ApolloClient({
networkInterface,
dataIdFromObject: o => o.id
});
和
const store = createStore(
combineReducers({
token: tokenReducer,
profile: profileReducer,
path: pathReducer,
apollo: client.reducer(),
}),
{}, // initial state
compose(
applyMiddleware(thunk, client.middleware(), logger),
)
);