0

我正在使用@vue/apollo-composableand开发一个 vue3 项目@graphql-codegen

我的索引页面执行搜索查询。该查询的每个结果在页面上都有一个磁贴。我希望缓存会回答切片查询,但相反,它们总是会错过。

在页面级别,我执行以下查询:

query getTokens($limit: Int!) {
    tokens(limit: $limit) {
        ...tokenInfo
    }
}

在我执行的 tile 组件内部:

query getToken($id: uuid!){
    token(id: $id) {
        ...tokenInfo
    }
}

片段如下所示:

fragment tokenInfo on token {
    id
    name
}

期望:缓存将处理 tile 组件内 100% 的查询。(我希望避免将这些数据序列化到 vuex 的失败)。

现实:我收到 n+1 个后端调用。我尝试了一堆排列,包括摆脱片段。如果我发送没有数据的getToken呼叫,fetchPolicy: 'cache-only'则返回。

apollo 客户端配置非常基础:


const cache = new InMemoryCache();

const defaultClient = new ApolloClient({
  uri: 'http://localhost:8080/v1/graphql',
  cache: cache,
  connectToDevTools: true,
});

const app = createApp(App)
  .use(Store, StateKey)
  .use(router)
  .provide(DefaultApolloClient, defaultClient);

我还附上了我的 apollo 开发工具的屏幕截图。看起来缓存实际上正在填充规范化数据:

阿波罗缓存截图

任何帮助将不胜感激!:)

4

1 回答 1

0

感谢@xadm 的评论以及我收到的关于 Vue 不和谐的一些反馈,我已经解决了这个问题。真的,我的困惑是因为我对这么多这些工具不熟悉。决定生活在边缘并成为 vue3 的早期采用者(我在很多方面都喜欢)让我更容易对现在文档质量的差异感到困惑。

也就是说,这就是我的解决方案。

问题:实际问题是,按照配置,Apollo 无法知道这一点getTokensgetToken返回相同的类型(token)。

解决方案:我发现解决此问题的最低配置如下:

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        token(_, { args, toReference }) {
          return toReference({
            __typename: 'token',
            id: args?.id,
          });
        },
      },
    },
  },
});

然而,感觉……对我来说有点恶心。理想情况下,我很想看到一种方法,只需将 apollo 指向我的模式副本或模式自省,并让它为我解决这个问题。如果有人知道更好的方法,请告诉我。

更好(?)解决方案:在短期内,我觉得这是一个更具可扩展性的解决方案:

type CacheRedirects = Record<string, FieldReadFunction>;

function generateCacheRedirects(types: string[]): CacheRedirects {
  const redirects: CacheRedirects = {};

  for (const type of types) {
    redirects[type] = (_, { args, toReference }) => {
      return toReference({
        __typename: type,
        id: args?.id,
      });
    };
  }

  return redirects;
}

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        ...generateCacheRedirects(['token']),
      },
    },
  },
});

如果有人对这些有任何改进,请添加评论/解决方案!:)

于 2021-02-17T19:17:03.093 回答