Skip to content

Commit

Permalink
Refactor writeRoot to run updaters as side-effects (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten committed Aug 20, 2019
1 parent e0ec178 commit 4612324
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
31 changes: 17 additions & 14 deletions src/operations/write.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ export const write = (
if (operation.operation === 'query') {
writeSelection(ctx, 'Query', select, data);
} else {
writeRoot(ctx, select, data);
const isMutation = operation.operation === 'mutation';
writeRoot(ctx, isMutation, select, data);
}

clearStoreState();
Expand Down Expand Up @@ -206,26 +207,19 @@ const writeField = (
};

// This is like writeSelection but assumes no parent entity exists
const writeRoot = (ctx: Context, select: SelectionSet, data: Data) => {
const writeRoot = (
ctx: Context,
isMutation: boolean,
select: SelectionSet,
data: Data
) => {
const { fragments, variables } = ctx;
forEachFieldNode(select, fragments, variables, node => {
const fieldName = getName(node);
const fieldAlias = getFieldAlias(node);
const fieldArgs = getFieldArguments(node, variables);
const fieldValue = data[fieldAlias];

if (ctx.store.updates[fieldName]) {
// TODO: Should this really always replace the default logic?
// If it does, there's no way for the user to write everything else to the store
// It should probably run after the default writeRootField
return ctx.store.updates[fieldName](
data,
fieldArgs || {},
ctx.store,
ctx
);
}

if (
node.selectionSet !== undefined &&
fieldValue !== null &&
Expand All @@ -234,6 +228,15 @@ const writeRoot = (ctx: Context, select: SelectionSet, data: Data) => {
const { selections: fieldSelect } = node.selectionSet;
writeRootField(ctx, fieldValue, fieldSelect);
}

if (isMutation) {
// We run side-effect updates after the default, normalized updates
// so that the data is already available in-store if necessary
const updater = ctx.store.updates[fieldName];
if (updater !== undefined) {
updater(data, fieldArgs || {}, ctx.store, ctx);
}
}
});
};

Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export type UpdateResolver<T = any> = (
) => void;

export interface UpdatesConfig {
[fieldName: string]: UpdateResolver;
[mutationFieldName: string]: UpdateResolver;
}

export type OptimisticMutationResolver = (
Expand Down

0 comments on commit 4612324

Please sign in to comment.