Skip to content

Commit 76e3ac1

Browse files
committed
Merge pull request #289 from graphql/printer
Provides a correct OperationType without name in GraphQLPrinter
2 parents 72e90c0 + 6741c31 commit 76e3ac1

File tree

2 files changed

+44
-3
lines changed

2 files changed

+44
-3
lines changed

src/language/__tests__/printer.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,44 @@ describe('Printer', () => {
3434
);
3535
});
3636

37+
it('correctly prints non-query operations without name', () => {
38+
const queryAstShorthanded = parse(`query { id, name }`);
39+
expect(print(queryAstShorthanded)).to.equal(
40+
`{
41+
id
42+
name
43+
}
44+
`);
45+
46+
const mutationAst = parse(`mutation { id, name }`);
47+
expect(print(mutationAst)).to.equal(
48+
`mutation {
49+
id
50+
name
51+
}
52+
`);
53+
54+
const queryAstWithArtifacts = parse(
55+
`query ($foo: TestType) @testDirective { id, name }`
56+
);
57+
expect(print(queryAstWithArtifacts)).to.equal(
58+
`query ($foo: TestType) @testDirective {
59+
id
60+
name
61+
}
62+
`);
63+
64+
const mutationAstWithArtifacts = parse(
65+
`mutation ($foo: TestType) @testDirective { id, name }`
66+
);
67+
expect(print(mutationAstWithArtifacts)).to.equal(
68+
`mutation ($foo: TestType) @testDirective {
69+
id
70+
name
71+
}
72+
`);
73+
});
74+
3775

3876
const kitchenSink = readFileSync(
3977
join(__dirname, '/kitchen-sink.graphql'),

src/language/printer.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,14 @@ const printDocASTReducer = {
2828
OperationDefinition(node) {
2929
const op = node.operation;
3030
const name = node.name;
31-
const defs = wrap('(', join(node.variableDefinitions, ', '), ')');
31+
const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');
3232
const directives = join(node.directives, ' ');
3333
const selectionSet = node.selectionSet;
34-
return !name ? selectionSet :
35-
join([ op, join([ name, defs ]), directives, selectionSet ], ' ');
34+
// Anonymous queries with no directives or variable definitions can use
35+
// the query short form.
36+
return !name && !directives && !varDefs && op === 'query' ?
37+
selectionSet :
38+
join([ op, join([ name, varDefs ]), directives, selectionSet ], ' ');
3639
},
3740

3841
VariableDefinition: ({ variable, type, defaultValue }) =>

0 commit comments

Comments
 (0)