Reputation: 43
I have a case where I have an interface
, which has different type
implementations defined in graphql. I may not be able to share the exact code. But the case looks something like:
interface Character {
name: String!
}
type Human implements Character {
name: String!
friends: [Character]
}
type Droid implements Character {
name: String!
material: String
}
There is query which returns either Human
or Droid
type in response.
Response may contain something like:
{
name: 'Human_01',
friends: []
__typename: 'Human'
}
or
{
name: 'Droid_01',
material: 'Aluminium'
__typename: 'Droid'
}
I am using Apollo Client 3 on client side for querying the data and have fragments for these like:
fragment Human on Human {
friends
}
fragment Droid on Droid {
material
}
fragment Character on Character {
name
...Human
...Droid
}
I am querying for the Character
data as:
character {
...Character
}
Since, this is the case of interface
, and as defined in the docs for Apollo client 3, we need to use possibleTypes
in order to match the fragments in such cases. For caching purpose, I have defined InMemoryCache as:
new InMemoryCache({ possibleTypes: { Character: ['Human', 'Droid'] } })
The primary key field for a Character
implementation is the name
field, which I need to use in order to store its value in cache.
In Apollo client 3, it is mentioned to use typePolicies
for defining keyFields
for a type.
So, I need to ask as to whether I should define, type policy for both type implementations, specifying keyFields
as name
in both cases like:
new InMemoryCache({
possibleTypes: { Character: ['Human', 'Droid'] },
typePolicies: { Human: { keyFields: ['name'] }, Droid: { keyFields: ['name'] } }
});
In my example, I have provided only 2 such type implementations but there can be n
number of type implementations corresponding to Character
interface. So, in that case I will need to define keyFields
as name
in typePolicies
for all the n
type implementations.
So, does there exist any better way of implementing caching wrt these types of interface
implementations ?
Any help would really be appreciated. Thanks!!!
Upvotes: 2
Views: 685
Reputation: 585
Inheritance of type and field policies is coming in the next minor version of @apollo/client
, v3.3!
You can try it out now by installing @apollo/[email protected]
.
To stay up to date on the progress of the v3.3 release, see this pull request.
Upvotes: 1