Skip to content

Commit 4ef0428

Browse files
authored
Address empty selection-set (#4291)
Backports #4228 from v17
1 parent 10cc0ac commit 4ef0428

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

src/validation/__tests__/ScalarLeafsRule-test.ts

+41-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
import { describe, it } from 'mocha';
22

3+
import { expectJSON } from '../../__testUtils__/expectJSON';
4+
5+
import type { DocumentNode } from '../../language/ast';
6+
import { OperationTypeNode } from '../../language/ast';
7+
import { Kind } from '../../language/kinds';
8+
39
import { ScalarLeafsRule } from '../rules/ScalarLeafsRule';
10+
import { validate } from '../validate';
411

5-
import { expectValidationErrors } from './harness';
12+
import { expectValidationErrors, testSchema } from './harness';
613

714
function expectErrors(queryStr: string) {
815
return expectValidationErrors(ScalarLeafsRule, queryStr);
@@ -126,4 +133,37 @@ describe('Validate: Scalar leafs', () => {
126133
},
127134
]);
128135
});
136+
137+
it('object type having only one selection', () => {
138+
const doc: DocumentNode = {
139+
kind: Kind.DOCUMENT,
140+
definitions: [
141+
{
142+
kind: Kind.OPERATION_DEFINITION,
143+
operation: OperationTypeNode.QUERY,
144+
selectionSet: {
145+
kind: Kind.SELECTION_SET,
146+
selections: [
147+
{
148+
kind: Kind.FIELD,
149+
name: { kind: Kind.NAME, value: 'human' },
150+
selectionSet: { kind: Kind.SELECTION_SET, selections: [] },
151+
},
152+
],
153+
},
154+
},
155+
],
156+
};
157+
158+
// We can't leverage expectErrors since it doesn't support passing in the
159+
// documentNode directly. We have to do this because this is technically
160+
// an invalid document.
161+
const errors = validate(testSchema, doc, [ScalarLeafsRule]);
162+
expectJSON(errors).toDeepEqual([
163+
{
164+
message:
165+
'Field "human" of type "Human" must have at least one field selected.',
166+
},
167+
]);
168+
});
129169
});

src/validation/rules/ScalarLeafsRule.ts

+9
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,15 @@ export function ScalarLeafsRule(context: ValidationContext): ASTVisitor {
4141
{ nodes: node },
4242
),
4343
);
44+
} else if (selectionSet.selections.length === 0) {
45+
const fieldName = node.name.value;
46+
const typeStr = inspect(type);
47+
context.reportError(
48+
new GraphQLError(
49+
`Field "${fieldName}" of type "${typeStr}" must have at least one field selected.`,
50+
{ nodes: node },
51+
),
52+
);
4453
}
4554
}
4655
},

0 commit comments

Comments
 (0)