Skip to content
This repository has been archived by the owner on Jul 6, 2020. It is now read-only.

Skip writing undefined fields and warn in dev #71

Merged
merged 2 commits into from
Sep 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/operations/write.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,21 @@ describe('Query', () => {
expect(console.warn).toHaveBeenCalledTimes(2);
expect((console.warn as any).mock.calls[0][0]).toMatch(/writer/);
});

it('should skip undefined values that are expected', () => {
const query = gql`
{
field
}
`;

write(store, { query }, { field: 'test' } as any);
// This should not overwrite the field
write(store, { query }, { field: undefined } as any);
// Because of us writing an undefined field
expect(console.warn).toHaveBeenCalledTimes(1);
expect((console.warn as any).mock.calls[0][0]).toMatch(/undefined/);
// The field must still be `'test'`
expect(store.getRecord('Query.field')).toBe('test');
});
});
39 changes: 30 additions & 9 deletions src/operations/write.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ interface Context {
store: Store;
variables: Variables;
fragments: Fragments;
isOptimistic?: boolean;
schemaPredicates?: SchemaPredicates;
}

Expand All @@ -53,11 +54,8 @@ export const write = (
data: Data
): WriteResult => {
initStoreState(0);

const result = startWrite(store, request, data);

clearStoreState();

return result;
};

Expand Down Expand Up @@ -107,6 +105,10 @@ export const writeOptimistic = (
schemaPredicates: store.schemaPredicates,
};

if (process.env.NODE_ENV === 'development') {
ctx.isOptimistic = true;
}

const operationName = ctx.store.getRootKey(operation.operation);
if (operationName === ctx.store.getRootKey('mutation')) {
const select = getSelectionSet(operation);
Expand Down Expand Up @@ -204,12 +206,31 @@ const writeSelection = (

if (isQuery) addDependency(fieldKey);

if (
process.env.NODE_ENV !== 'production' &&
ctx.schemaPredicates &&
typename
) {
ctx.schemaPredicates.isFieldAvailableOnType(typename, fieldName);
if (process.env.NODE_ENV !== 'production') {
if (fieldValue === undefined) {
const advice = ctx.isOptimistic
? '\nYour optimistic result may be missing a field!'
: '';

const expected =
node.selectionSet === undefined
? 'scalar (number, boolean, etc)'
: 'selection set';

warning(
false,
'Invalid value: The field at `' +
fieldKey +
'` is `undefined`, but the GraphQL query expects a ' +
expected +
' for this field.' +
advice
);

continue; // Skip this field
} else if (ctx.schemaPredicates && typename) {
ctx.schemaPredicates.isFieldAvailableOnType(typename, fieldName);
}
}

if (node.selectionSet === undefined) {
Expand Down