如何将令牌设置为onError ApolloClient?

时间:2019-05-11 03:44:45

标签: react-native graphql apollo react-apollo apollo-client

如果返回错误将再次调用setContext进行查询,我想处理错误,但是由于onError不接受异步,所以我无法获得本地状态的令牌。我该怎么做。 谢谢

//
export default async () =>
  new ApolloClient({
    cache: new InMemoryCache({
      dataIdFromObject: object => object.key || null
    }),
    uri: Api.GRAPH_QL_URL,
    clientState: { defaults, resolvers },

    // cho handle network failed
///onError not accept async
    onError: ({ graphQLErrors, networkError, operation, forward }) => {
      // how to get token in hear
      if (networkError) {
        operation.setContext({
          headers: {
            Accept: "application/json",
            authorization: token !== null ? `JWT ${token}` : ""   // how to put token into authorization
          }
        });
      }
    },
// Call query
    request: async operation => {
      const token = await AsyncStorage.getItem(strings.keyToken);

      console.log("Client request: ", {
        operationName: operation.operationName,
        variables: operation.variables,
        query: operation.query,
        jwtoken: token
      });
      operation.setContext({
        headers: {
          Accept: "application/json",
          authorization: token !== null ? `JWT ${token}` : ""
        }
      });
    },
  });
  //I want to handle error if return error will call setContext for query again but I can't get token in local state. How I can do that.
Thanks

1 个答案:

答案 0 :(得分:0)

您需要设置一个Observable才能在async/await方法中使用onError

apollo-linkimport { Observable } from 'apollo-link';)导入。

onError: ({ graphQLErrors, networkError, operation, forward }) => {
  if (networkError) {
    return new Observable(async (observer) => {
      const token = await AsyncStorage.getItem(strings.keyToken);

      const headers = operation.getContext().headers;

      operation.setContext({
        headers: {
          ...headers,
          Authorization: token !== null ? `JWT ${token}` : ''              
        }
      });

      const subscriber = {
        next: observer.next.bind(observer),
        error: observer.error.bind(observer),
        complete: observer.complete.bind(observer),
      };

      return forward(operation).subscribe(subscriber);
    });
  }
}