Apollo Client 3:如何在客户端为 graphql 接口实现缓存?

Apollo Client 3: How to implement caching on client side for graphql interfaces?

我有一个案例,我有一个 interface,它在 graphql 中定义了不同的 type 实现。我可能无法分享确切的代码。但是案例看起来像:

interface Character {
  name: String!
}
type Human implements Character {
  name: String!
  friends: [Character]
}

type Droid implements Character {
  name: String!
  material: String
}

有 returns HumanDroid 类型的查询作为响应。

响应可能包含如下内容:

{
  name: 'Human_01',
  friends: []
  __typename: 'Human'
}

{
  name: 'Droid_01',
  material: 'Aluminium'
  __typename: 'Droid'
}

我在客户端使用 Apollo Client 3 来查询数据,并且有这样的片段:

fragment Human on Human {
 friends
}

fragment Droid on Droid {
 material
}

fragment Character on Character {
  name
  ...Human
  ...Droid
}


我查询 Character 数据为:

 character {
  ...Character
 }

因为,这是 interface 的情况,并且根据 Apollo 客户端 3 的文档中的定义,我们需要使用 possibleTypes 来匹配这种情况下的片段。出于缓存目的,我将 InMemoryCache 定义为:

new InMemoryCache({ possibleTypes: { Character: ['Human', 'Droid'] } })

Character 实现的主键字段是 name 字段,我需要使用它来将其值存储在缓存中。

在Apollo client 3中提到使用typePolicies来定义keyFields类型。

因此,我需要询问是否应该为两种类型的实现定义类型策略,在两种情况下都将 keyFields 指定为 name,例如:

new InMemoryCache({ 
    possibleTypes: { Character: ['Human', 'Droid'] }, 
    typePolicies: { Human: { keyFields: ['name'] }, Droid: { keyFields: ['name'] } } 
});

在我的例子中,我只提供了 2 个这样的类型实现,但是可以有 n 个对应于 Character 接口的类型实现。因此,在那种情况下,我需要将 keyFields 定义为 typePolicies 中的 name,用于所有 n 类型的实现。

那么,对于这些类型的 interface 实现,是否存在更好的实现缓存的方法?

任何帮助将不胜感激。谢谢!!!

Inheritance of type and field policies 将在 @apollo/client 的下一个次要版本 v3.3!

中推出

您现在可以通过安装 @apollo/client@3.3.0-beta.5 来试用它。

要了解 v3.3 版本的最新进展,请参阅 this pull request