Skip to content

Commit

Permalink
Avoid freezing user-provided scalar field values.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn committed Aug 21, 2019
1 parent 2643dbb commit af94014
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
37 changes: 37 additions & 0 deletions packages/apollo-cache-inmemory/src/__tests__/writeToStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { StoreWriter } from '../writeToStore';
import { defaultNormalizedCacheFactory } from '../entityCache';

import { makeReference } from '../helpers';
import { InMemoryCache } from '../inMemoryCache';

export function withWarning(func: Function, regex?: RegExp) {
let message: string = null as never;
Expand Down Expand Up @@ -1862,4 +1863,40 @@ describe('writing to the store', () => {
},
});
});

it('should not deep-freeze scalar objects', () => {
const query = gql`
query {
scalarFieldWithObjectValue
}
`;

const scalarObject = {
a: 1,
b: [2, 3],
c: {
d: 4,
e: 5,
},
};

const cache = new InMemoryCache();

cache.writeQuery({
query,
data: {
scalarFieldWithObjectValue: scalarObject,
},
});

expect(Object.isFrozen(scalarObject)).toBe(false);
expect(Object.isFrozen(scalarObject.b)).toBe(false);
expect(Object.isFrozen(scalarObject.c)).toBe(false);

const result = cache.readQuery<any>({ query });
expect(result.scalarFieldWithObjectValue).not.toBe(scalarObject);
expect(Object.isFrozen(result.scalarFieldWithObjectValue)).toBe(true);
expect(Object.isFrozen(result.scalarFieldWithObjectValue.b)).toBe(true);
expect(Object.isFrozen(result.scalarFieldWithObjectValue.c)).toBe(true);
});
});
6 changes: 5 additions & 1 deletion packages/apollo-cache-inmemory/src/writeToStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
StoreValue,
DeepMerger,
getTypenameFromResult,
cloneDeep,
} from 'apollo-utilities';

import { invariant, InvariantError } from 'ts-invariant';
Expand Down Expand Up @@ -233,7 +234,10 @@ export class StoreWriter {
context: WriteContext,
): StoreValue {
if (!field.selectionSet || value === null) {
return value;
// In development, we need to clone scalar values so that they can be
// safely frozen with maybeDeepFreeze in readFromStore.ts. In production,
// it's cheaper to store the scalar values directly in the cache.
return process.env.NODE_ENV === 'production' ? value : cloneDeep(value);
}

if (Array.isArray(value)) {
Expand Down

0 comments on commit af94014

Please sign in to comment.