Configure Apollo Client's cache to automatically add __typename
field selections, which concrete types implement the Node
interface, and the type-policies needed to read the watch query data from the store:
import { InMemoryCache } from "@apollo/client";
import { typePoliciesWithGlobalObjectIdStoreKeys as typePolicies } from "@graphitation/apollo-react-relay-duct-tape";
const cache = new InMemoryCache({
addTypename: true,
possibleTypes: {
Node: ["Todo"],
},
typePolicies: {
Query: {
fields: {
__fragments: {
read: typePolicies.Query.fields.__fragments.read,
},
node: {
read: typePolicies.Query.fields.node.read,
},
},
},
Node: {
fields: {
__fragments: {
read: typePolicies.Node.fields.__fragments.read,
},
},
},
},
dataIdFromObject(responseObject, keyFieldsContext) {
if (
responseObject.id &&
responseObject.__typename &&
possibleTypes?.Node.includes(responseObject.__typename)
) {
return responseObject.id as string;
}
return defaultDataIdFromObject(responseObject, keyFieldsContext);
},
});
In most cases as in the example app, you can just build the configuration using utilities exported from @graphitation/apollo-react-relay-duct-tape
:
import { InMemoryCache, defaultDataIdFromObject } from "@apollo/client";
import { schema } from "fileWithYourSchema";
import {
typePoliciesWithGlobalObjectIdStoreKeys,
getPossibleTypesAndDataIdFromNode,
} from "@graphitation/apollo-react-relay-duct-tape";
const { possibleTypes, dataIdFromObject } =
getPossibleTypesAndDataIdFromNode(schema);
const cache = new InMemoryCache({
addTypename: true,
possibleTypes,
typePolicies: typePoliciesWithGlobalObjectIdStoreKeys,
dataIdFromObject(responseObject, keyFieldsContext) {
return (
dataIdFromNode(responseObject, keyFieldsContext) ||
defaultDataIdFromObject(responseObject, keyFieldsContext)
);
},
});