Skip to content
Open
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
33 changes: 32 additions & 1 deletion packages/plugin/src/rules/require-selections/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ const USER_POST_SCHEMA = /* GraphQL */ `
type Post {
id: ID
title: String
content: String
author: [User!]!
}

Expand Down Expand Up @@ -316,6 +317,30 @@ ruleTester.run<RuleOptions, true>('require-selections', rule, {
}
`,
},
{
name: 'should require only extant fields with `requireAllFields` option',
code: /* GraphQL */ `
{
user {
id
posts {
id
title
content
}
}
}
`,
options: [{ requireAllFields: true, fieldName: ['id', 'title', 'content'] }],
parserOptions: {
graphQLConfig: {
schema: USER_POST_SCHEMA,
documents: `
fragment Example on User { id }
`,
},
},
},
],
invalid: [
{
Expand Down Expand Up @@ -523,7 +548,13 @@ ruleTester.run<RuleOptions, true>('require-selections', rule, {
documents: '{ foo }',
},
},
errors: 1,
errors: [
{
message:
"Field `hasId.name` must be selected when it's available on a type.\n" +
'Include it in your selection set.',
},
],
},
],
});
15 changes: 11 additions & 4 deletions packages/plugin/src/rules/require-selections/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,20 +201,27 @@ export const rule: GraphQLESLintRule<RuleOptions, true> = {

function checkFields(rawType: GraphQLInterfaceType | GraphQLObjectType) {
const fields = rawType.getFields();
const hasIdFieldInType = idNames.some(name => fields[name]);

if (!hasIdFieldInType) {
// Only check fields which are actually present on this type
const idFieldsInType = idNames.filter(name => fields[name]);

// Type doesn't implement any of the `fieldNames`
if (idFieldsInType.length === 0) {
return;
}

checkFragments(node as GraphQLESTreeNode<SelectionSetNode>);

if (requireAllFields) {
for (const idName of idNames) {
for (const idName of idFieldsInType) {
// For each `fieldName` present on this type, check it's in the
// selection separately
report([idName]);
}
} else {
report(idNames);
// Pass the `fieldNames` present on this type together; `report` will
// pass if _any_ of them are selected
report(idFieldsInType);
}
}

Expand Down