Skip to content

Address empty selection-set #4291

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

Merged
merged 1 commit into from
Nov 8, 2024
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
42 changes: 41 additions & 1 deletion src/validation/__tests__/ScalarLeafsRule-test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { describe, it } from 'mocha';

import { expectJSON } from '../../__testUtils__/expectJSON';

import type { DocumentNode } from '../../language/ast';
import { OperationTypeNode } from '../../language/ast';
import { Kind } from '../../language/kinds';

import { ScalarLeafsRule } from '../rules/ScalarLeafsRule';
import { validate } from '../validate';

import { expectValidationErrors } from './harness';
import { expectValidationErrors, testSchema } from './harness';

function expectErrors(queryStr: string) {
return expectValidationErrors(ScalarLeafsRule, queryStr);
Expand Down Expand Up @@ -126,4 +133,37 @@ describe('Validate: Scalar leafs', () => {
},
]);
});

it('object type having only one selection', () => {
const doc: DocumentNode = {
kind: Kind.DOCUMENT,
definitions: [
{
kind: Kind.OPERATION_DEFINITION,
operation: OperationTypeNode.QUERY,
selectionSet: {
kind: Kind.SELECTION_SET,
selections: [
{
kind: Kind.FIELD,
name: { kind: Kind.NAME, value: 'human' },
selectionSet: { kind: Kind.SELECTION_SET, selections: [] },
},
],
},
},
],
};

// We can't leverage expectErrors since it doesn't support passing in the
// documentNode directly. We have to do this because this is technically
// an invalid document.
const errors = validate(testSchema, doc, [ScalarLeafsRule]);
expectJSON(errors).toDeepEqual([
{
message:
'Field "human" of type "Human" must have at least one field selected.',
},
]);
});
});
9 changes: 9 additions & 0 deletions src/validation/rules/ScalarLeafsRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ export function ScalarLeafsRule(context: ValidationContext): ASTVisitor {
{ nodes: node },
),
);
} else if (selectionSet.selections.length === 0) {
const fieldName = node.name.value;
const typeStr = inspect(type);
context.reportError(
new GraphQLError(
`Field "${fieldName}" of type "${typeStr}" must have at least one field selected.`,
{ nodes: node },
),
);
}
}
},
Expand Down
Loading