【问题标题】:How to access apollo client in apollo-link-error to resetStore?如何在 apollo-link-error 中访问 apollo 客户端以重置存储?
【发布时间】:2019-01-10 20:52:06
【问题描述】:

我正在构建一个基于JWT的认证系统。

JWT 已过期。当JWT 过期时,我使用apollo-link-error 捕获JWT 过期错误。我想调用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])
});

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

【问题讨论】:

    标签: apollo react-apollo apollo-client


    【解决方案1】:

    您应该可以直接调用客户端:

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

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

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

    【讨论】:

    • 对我来说也不是。
    【解决方案2】:

    Mikael 的回答对我有用。 只需使用 client.resetStore();在 onError 中,就像 Mikael 的回答一样。

    但是,也请确保将 errorLink 链接到客户端,如下面的示例:

    const client = new ApolloClient({
      cache,
      link: authLink.concat(errorLink).concat(restLink).concat(httpLink),
      resolvers
    });
    

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2020-07-17
      • 2018-07-30
      • 2018-07-23
      • 2017-03-18
      • 2018-04-17
      • 2021-04-04
      • 2019-06-30
      • 2019-04-17
      相关资源
      最近更新 更多