Skip to content

Commit af4337f

Browse files
committed
Add support for mutations that don't specify return fields
1 parent 4a9ecbb commit af4337f

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"scripts": {
77
"build": "tslint -p . && tsc",
88
"test": "mocha -r ts-node/register --recursive \"./src/**/__tests__/*\"",
9+
"test-watch": "mocha -r ts-node/register --recursive \"./src/**/__tests__/*\" --watch --watch-extensions ts,tsx",
910
"prepublish": "npm run build && npm run test"
1011
},
1112
"typings": "lib/index.d.ts",

src/__tests__/jsonToGraphQLQuery.tests.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,23 @@ describe('jsonToGraphQL()', () => {
156156
}`);
157157
});
158158

159+
it('correctly converts mutations with no specified return fields', () => {
160+
const query = {
161+
mutation: {
162+
create_post: {
163+
__args: {
164+
title: 'My Awesome Post',
165+
body: 'This post is awesome!'
166+
}
167+
}
168+
}
169+
};
170+
expect(jsonToGraphQLQuery(query, { pretty: true })).to.equal(
171+
`mutation {
172+
create_post (title: "My Awesome Post", body: "This post is awesome!")
173+
}`);
174+
});
175+
159176
it('works with pretty mode turned off', () => {
160177
const query = {
161178
query: {

src/jsonToGraphQLQuery.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,22 @@ function convertQuery(node: any, level: number, output: Array<[string, number]>)
3030
for (const key in node) {
3131
if (key != '__args') {
3232
if (typeof node[key] == 'object') {
33+
const fieldCount = Object.keys(node[key]).length;
34+
let token: string;
35+
let subFields: boolean;
3336
if (typeof node[key].__args == 'object') {
34-
output.push([`${key} (${buildArgs(node[key].__args)}) {`, level]);
37+
token = `${key} (${buildArgs(node[key].__args)})`;
38+
subFields = fieldCount > 1;
3539
}
3640
else {
37-
output.push([`${key} {`, level]);
41+
token = `${key}`;
42+
subFields = fieldCount > 0;
3843
}
44+
output.push([token + (subFields ? ' {' : ''), level]);
3945
convertQuery(node[key], level + 1, output);
40-
output.push(['}', level]);
46+
if (subFields) {
47+
output.push(['}', level]);
48+
}
4149
}
4250
else {
4351
output.push([`${key}`, level]);

0 commit comments

Comments
 (0)