2

我在 React-Native 应用程序中使用 Apollo(带有 Graph Cool)、redux 和 Auth0。我试图延迟查询和突变,直到设置标题。

idToken 存储在异步存储中,因此是一个承诺。我不能使用 redux 来传递令牌,因为这会产生循环依赖。

当用户第一次登录或令牌已过期时,在设置标头之前发送查询,这意味着我收到错误Error: GraphQL error: Insufficient Permissions在此处输入图像描述

如何延迟查询,直到找到令牌并将其添加到标头?我一直在寻找三个主要的解决方案:

  1. 添加 forceFetch: true; 这似乎是 Apollo 客户端早期实现的一部分。即使我找到了等价物,该应用程序在第一次尝试获取时仍然失败。
  2. 登录时重置商店(补水?)。这仍然是异步的,所以我看不出这会如何影响结果。
  3. 从登录本身中删除所有突变和查询,但是由于应用程序的进度,这是不可行的。

一些片段:

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),
  )
);
4

1 回答 1

3

我不确定如果没有复制应用程序这将起作用,主要是因为我没有设置您的结构的应用程序,但是您遇到了这种竞争条件,因为您在异步链之外调用 next()。

在当前位置调用 next() 将告诉客户端继续请求,即使您的令牌未设置。相反,让我们等到令牌返回并设置标头后再继续。

networkInterface.use([{
  applyMiddleware(req, next) {
    if(!req.options.headers) {
      req.options.headers = {}
    }
    AsyncStorage.getItem('token')
      .then(myToken => {
         req.options.headers.authorization = `Bearer ${myToken}`;
      })
      .then(next)  // call next() after authorization header is set.
      .catch(err => console.log(err));   
  }
}]);
于 2017-04-06T06:49:56.647 回答