Skip to content

Commit

Permalink
Make cache.identify return undefined instead of throwing.
Browse files Browse the repository at this point in the history
Should help with `cache.identify`-related cases of issue #6673.
  • Loading branch information
benjamn committed Aug 25, 2021
1 parent 0f6e613 commit 751802a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
16 changes: 13 additions & 3 deletions src/cache/inmemory/__tests__/entityStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1772,9 +1772,19 @@ describe('EntityStore', () => {
c: 3,
})).toBe('ABCs:{"b":2,"a":1,"c":3}');

expect(() => cache.identify(ABCs)).toThrowError(
"Missing field 'b' while computing key fields",
);
{ // TODO Extact this to a helper function.
const consoleWarnSpy = jest.spyOn(console, "warn");
consoleWarnSpy.mockImplementation(() => {});
try {
expect(cache.identify(ABCs)).toBeUndefined();
expect(consoleWarnSpy).toHaveBeenCalledTimes(1);
expect(consoleWarnSpy).toHaveBeenCalledWith(
new Error("Missing field 'b' while computing key fields")
);
} finally {
consoleWarnSpy.mockRestore();
}
}

expect(cache.readFragment({
id: cache.identify({
Expand Down
9 changes: 7 additions & 2 deletions src/cache/inmemory/inMemoryCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import './fixPolyfills';
import { DocumentNode } from 'graphql';
import { OptimisticWrapperFunction, wrap } from 'optimism';
import { equal } from '@wry/equality';
import { invariant } from 'ts-invariant';

import { ApolloCache } from '../core/cache';
import { Cache } from '../core/types/Cache';
Expand Down Expand Up @@ -334,8 +335,12 @@ export class InMemoryCache extends ApolloCache<NormalizedCacheObject> {
// sure that none of the primary key fields have been renamed by aliasing.
// If you pass a Reference object, its __ref ID string will be returned.
public identify(object: StoreObject | Reference): string | undefined {
return isReference(object) ? object.__ref :
this.policies.identify(object)[0];
if (isReference(object)) return object.__ref;
try {
return this.policies.identify(object)[0];
} catch (e) {
invariant.warn(e);
}
}

public evict(options: Cache.EvictOptions): boolean {
Expand Down

0 comments on commit 751802a

Please sign in to comment.