Skip to content
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
18 changes: 15 additions & 3 deletions src/rules.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,20 @@ export function OperationsMustHaveNames(context) {
};
}

function getFieldWasRequestedOnNode(node, field, recursing = false) {
return node.selectionSet.selections.some(n => {
// If it's an inline fragment, we need to look deeper
if (n.kind === 'InlineFragment' && !recursing) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i actually wonder if we do need to keep recursing — is it possible to have inline fragments inside inline fragments?

i'll leave this for now since this unblocks some breaking behavior

return getFieldWasRequestedOnNode(n, field, true);
}
if (n.kind === 'FragmentSpread') {
// We don't know if the field was requested in this case, so default to not erroring.
return true;
}
return n.name.value === field;
});
}

export function RequiredFields(context, options) {
return {
Field(node) {
Expand All @@ -32,9 +46,7 @@ export function RequiredFields(context, options) {
fieldAvaliableOnOfType = recursivelyCheckOnType(def.type.ofType, field);
}
if (fieldAvaliableOnType || fieldAvaliableOnOfType) {
const fieldWasRequested = !!node.selectionSet.selections.find(
n => (n.name.value === field || n.kind === 'FragmentSpread')
);
const fieldWasRequested = getFieldWasRequestedOnNode(node, field);
if (!fieldWasRequested) {
context.reportError(
new GraphQLError(`'${field}' field required on '${node.name.value}'`, [node])
Expand Down
12 changes: 11 additions & 1 deletion test/makeRule.js
Original file line number Diff line number Diff line change
Expand Up @@ -856,7 +856,8 @@ const requiredFieldsTestCases = {
pass: [
'const x = gql`query { allFilms { films { title } } }`',
'const x = gql`query { stories { id comments { text } } }`',
'const x = gql`query { greetings { id, hello, foo } }`'
'const x = gql`query { greetings { id, hello, foo } }`',
'const x = gql`query { greetings { hello ... on Greetings { id } } }`',
],
fail: [
{
Expand All @@ -873,6 +874,15 @@ const requiredFieldsTestCases = {
type: 'TaggedTemplateExpression',
}],
},
{
code: 'const x = gql`query { greetings { hello ... on Greetings { foo } } }`',
errors: [
{
message: `'id' field required on 'greetings'`,
type: 'TaggedTemplateExpression',
},
],
},
],
};

Expand Down