Skip to content

Commit

Permalink
Support keyFields:false in TypePolicy to disable normalization.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn committed Oct 15, 2019
1 parent ad2027f commit 7b72713
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
8 changes: 8 additions & 0 deletions src/cache/inmemory/__tests__/policies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,13 @@ describe("type policies", function () {
const cache = new InMemoryCache({
typePolicies: {
Person: {
// Disables normalization for the Person type, which means the
// todos field will be nested inside a non-normalized object
// (with __typename "Person") directly under the ROOT_QUERY.me
// field, which exercises what happens when mergeOverrides
// becomes nested (see writeToStore.ts).
keyFields: false,

fields: {
todos: {
keyArgs: [],
Expand Down Expand Up @@ -570,6 +577,7 @@ describe("type policies", function () {
data: {
me: {
__typename: "Person",
id: "ignored",
todos: [
{ __typename: "Todo", id: 1, text: "Write more merge tests" },
{ __typename: "Todo", id: 2, text: "Write pagination tests" },
Expand Down
15 changes: 11 additions & 4 deletions src/cache/inmemory/policies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ type KeyFieldsFunction = (
type TypePolicy = {
// Allows defining the primary key fields for this type, either using an
// array of field names or a function that returns an arbitrary string.
keyFields?: KeySpecifier | KeyFieldsFunction;
keyFields?: KeySpecifier | KeyFieldsFunction | false;

// In the rare event that your schema happens to use a different
// __typename for the root Query, Mutation, and/or Schema types, you can
Expand Down Expand Up @@ -133,6 +133,8 @@ export function defaultDataIdFromObject(object: StoreObject) {
return null;
}

const nullKeyFn: KeyFieldsFunction = () => null;

export type PossibleTypesMap = {
[supertype: string]: string[];
};
Expand Down Expand Up @@ -221,9 +223,14 @@ export class Policies {
if (incoming.mutationType) this.setRootTypename("Mutation", typename);
if (incoming.subscriptionType) this.setRootTypename("Subscription", typename);

existing.keyFn = Array.isArray(keyFields)
? keyFieldsFnFromSpecifier(keyFields)
: typeof keyFields === "function" ? keyFields : void 0;
existing.keyFn =
// Pass false to disable normalization for this typename.
keyFields === false ? nullKeyFn :
// Pass an array of strings to use those fields to compute a
// composite ID for objects of this typename.
Array.isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields) :
// Pass a function to take full control over identification.
typeof keyFields === "function" ? keyFields : void 0;

if (fields) {
Object.keys(fields).forEach(fieldName => {
Expand Down

0 comments on commit 7b72713

Please sign in to comment.