Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow mutations to return custom classes #349

Merged
merged 1 commit into from
Jun 29, 2021
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
36 changes: 35 additions & 1 deletion src/mutation/__tests__/mutation-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,43 @@ describe('mutationWithClientMutationId()', () => {
}
`;

expect(graphqlSync({ schema, source })).to.deep.equal({
data: { someMutation: null },
});
});

it('supports mutations returning custom classes', () => {
class SomeClass {
getSomeGeneratedData() {
return 1;
}
}

const someMutation = mutationWithClientMutationId({
name: 'SomeMutation',
inputFields: {},
outputFields: {
result: {
type: GraphQLInt,
resolve: (obj) => obj.getSomeGeneratedData(),
},
},
mutateAndGetPayload: () => new SomeClass(),
});
const schema = wrapInSchema({ someMutation });

const source = `
mutation {
someMutation(input: {clientMutationId: "abc"}) {
result
clientMutationId
}
}
`;

expect(graphqlSync({ schema, source })).to.deep.equal({
data: {
someMutation: { result: null, clientMutationId: 'abc' },
someMutation: { result: 1, clientMutationId: 'abc' },
},
});
});
Expand Down
12 changes: 10 additions & 2 deletions src/mutation/mutation.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,18 @@ export function mutationWithClientMutationId(
const { clientMutationId } = input;
const payload = mutateAndGetPayload(input, context, info);
if (isPromise(payload)) {
return payload.then((data) => ({ ...data, clientMutationId }));
return payload.then(injectClientMutationId);
}
return injectClientMutationId(payload);

return { ...payload, clientMutationId };
function injectClientMutationId(data: mixed) {
if (typeof data === 'object' && data !== null) {
// $FlowFixMe[cannot-write] It's bad idea to mutate data but we need to pass clientMutationId somehow. Maybe in future we figure out better solution satisfying all our test cases.
data.clientMutationId = clientMutationId;
}

return data;
}
},
};
}