阿波罗为什么不为此查询调用我的cacheRedirect?

时间:2018-07-19 13:13:57

标签: apollo apollo-client apollo-angular

使用apollo-angular,我有一个像这样的apollo InMemoryCache

new InMemoryCache({
  // ... stuff

  cacheRedirects: {
    Query: {
      form: (_, args, { getCacheKey }) => {
        console.log('cache key', [args, getCacheKey({ __typename: 'Form', id: args.formId })]);
        return getCacheKey({ __typename: 'Form', id: args.formId });
      },
    },
  },
});

运行此查询时,未调用form的cacheRedirect函数。

this.apollo.watchQuery({
  query: gql`
    query FormSummary($formId: ID!) {
      form(formId: $formId) {
        __typename
        id
        description
      }
    }   
  `,
  variables: { formId }
}).valueChanges

相反,查询只是(成功地)进入服务器,而忽略了表单(带有__typenameiddescription字段)已经在缓存中的事实。即使它不在缓存中,我也希望窗体的cacheRedirect函数仍然被调用。当我进行这个极其相似的查询时,表单的cacheRedirect被调用

this.apollo.watchQuery<any>({
  query: gql`
    query FormGet($formId: ID!) {
      form(formId: $formId) {
        ...WholeFormResponse
      }
    }
    ${Fragments.wholeFormResponse}
  `,
  variables: { formId: id },
}).valueChanges

我是否缺少有关cacheRedirects如何工作的明显提示?我的印象是,只要调用以query Form {}开头的查询,就应该运行form的cacheRedirect。

任何帮助将不胜感激!我想我缺少明显的东西了……

注意:我对cacheRedirect的理解是WholeFormResponse片段的内容无关紧要,因此我没有将它们包括在内。

更新

打开调试器并逐步执行一些代码,之所以没有调用我的cacheRedirect函数(在错误的示例中)是因为typeof fieldValue in this line of the apollo InMemoryCache source code !== 'undefined'。我还无法弄清楚为什么应该为我的极其相似的工作查询定义未定义,或者为什么它确实等于未定义。

1 个答案:

答案 0 :(得分:1)

经过7个小时的调试,我发现了!!!! :D

原来这是一个角度问题,而不是阿波罗问题。这两个查询(成功的查询和问题的查询)都在不同的角度服务中运行,而角度服务本身就是不同NgModules的每个部分。这两个父NgModule都导入并自定义了圆角ApolloModule。这导致 Apollo服务的两个单独实例

换一种说法,我的apollo客户端(和缓存)不是单例服务,它是重复的!一个服务的查询缓存未与其他服务共享/反之。

无论如何,清理完所有东西后,一切都会按预期进行。