Skip to content

Commit f221f03

Browse files
Allow mutations to return custom classes (#349)
1 parent fa978fb commit f221f03

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

src/mutation/__tests__/mutation-test.js

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,9 +195,43 @@ describe('mutationWithClientMutationId()', () => {
195195
}
196196
`;
197197

198+
expect(graphqlSync({ schema, source })).to.deep.equal({
199+
data: { someMutation: null },
200+
});
201+
});
202+
203+
it('supports mutations returning custom classes', () => {
204+
class SomeClass {
205+
getSomeGeneratedData() {
206+
return 1;
207+
}
208+
}
209+
210+
const someMutation = mutationWithClientMutationId({
211+
name: 'SomeMutation',
212+
inputFields: {},
213+
outputFields: {
214+
result: {
215+
type: GraphQLInt,
216+
resolve: (obj) => obj.getSomeGeneratedData(),
217+
},
218+
},
219+
mutateAndGetPayload: () => new SomeClass(),
220+
});
221+
const schema = wrapInSchema({ someMutation });
222+
223+
const source = `
224+
mutation {
225+
someMutation(input: {clientMutationId: "abc"}) {
226+
result
227+
clientMutationId
228+
}
229+
}
230+
`;
231+
198232
expect(graphqlSync({ schema, source })).to.deep.equal({
199233
data: {
200-
someMutation: { result: null, clientMutationId: 'abc' },
234+
someMutation: { result: 1, clientMutationId: 'abc' },
201235
},
202236
});
203237
});

src/mutation/mutation.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,18 @@ export function mutationWithClientMutationId(
9191
const { clientMutationId } = input;
9292
const payload = mutateAndGetPayload(input, context, info);
9393
if (isPromise(payload)) {
94-
return payload.then((data) => ({ ...data, clientMutationId }));
94+
return payload.then(injectClientMutationId);
9595
}
96+
return injectClientMutationId(payload);
9697

97-
return { ...payload, clientMutationId };
98+
function injectClientMutationId(data: mixed) {
99+
if (typeof data === 'object' && data !== null) {
100+
// $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.
101+
data.clientMutationId = clientMutationId;
102+
}
103+
104+
return data;
105+
}
98106
},
99107
};
100108
}

0 commit comments

Comments
 (0)