如何在 apollo-link-error 中访问 apollo 客户端到 resetStore?

sli*_*wp2 5 apollo react-apollo apollo-client

我正在构建一个基于JWT.

JWT已过期。当JWT到期时,我抓住JWT使用过期的错误apollo-link-error。我想调用apolloClient.resetStore()方法来重置缓存。

这是我的代码:

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(error => {
      // console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
      if (error.code === 1001) {
        auth.signout();

        // how can I get apollo client here?
        //client.resetStore();
      }
    });
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const client = new ApolloClient({
  cache,
  link: from([authMiddleware, errorLink, terminalLink])
});
Run Code Online (Sandbox Code Playgroud)

我不确定apollo-link-error是处理 expired 错误的正确位置JWT

Mik*_*ank 2

您应该能够直接调用客户端:

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    client.resetStore();
  }
});

const client = new ApolloClient({
  cache: new InMemoryCache({ fragmentMatcher }),
  link: ApolloLink.from([
    errorLink,
    // otherLink,
    // otherLink,
  ]),
});
Run Code Online (Sandbox Code Playgroud)

您甚至可以从嵌套配置函数中调用它:

const client = new ApolloClient({
  cache: new InMemoryCache({ fragmentMatcher }),
  link: ApolloLink.from([
    onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors) {
        client.resetStore();
      }
    }),
    // otherLink,
    // otherLink,
  ]),
});
Run Code Online (Sandbox Code Playgroud)