Skip to content

Commit

Permalink
fix required-fields rule to work with inline fragments without a fiel…
Browse files Browse the repository at this point in the history
…d ancestor
  • Loading branch information
henryqdineen committed Aug 15, 2019
1 parent 585288b commit 11ef5f3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 9 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

### vNEXT

- Update the `required-fields` rule to handle inline fragments without field ancestors. PR by [Henry Q. Dineen](https://github.com/henryqdineen)

### v3.0.3

- chore: Update dependency `graphql-tools` to `v4.0.4`. [PR #210](https://github.com/apollographql/eslint-plugin-graphql/pull/210)
Expand Down
22 changes: 13 additions & 9 deletions src/customGraphQLValidationRules.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,11 @@ export function RequiredFields(context, options) {

const ancestorClone = [...ancestors];

let nearestField;
let nearestFieldOrExecutableDefinition;
let nextAncestor;

// Now, walk up the ancestors, until you see a field.
while (!nearestField) {
// Now, walk up the ancestors, until you see a field or executable definition.
while (!nearestFieldOrExecutableDefinition) {
nextAncestor = ancestorClone.pop();

if (
Expand All @@ -77,19 +77,23 @@ export function RequiredFields(context, options) {
return true;
}

if (nextAncestor.kind === "Field") {
nearestField = nextAncestor;
if (
nextAncestor.kind === "Field" ||
nextAncestor.kind === "FragmentDefinition" ||
nextAncestor.kind === "OperationDefiniton"
) {
nearestFieldOrExecutableDefinition = nextAncestor;
}
}

// If we never found a field, the query is malformed
if (!nearestField) {
// If we never found a field or executable definition, the query is malformed
if (!nearestFieldOrExecutableDefinition) {
throw new Error(
"Inline fragment found inside document without a parent field."
"Inline fragment found inside document without a parent field, fragment definition, or operation definition."
);
}

// We found a field, but we never saw the field we were looking for in
// We found a field or executable definition, but we never saw the field we were looking for in
// the intermediate selection sets.
context.reportError(
new GraphQLError(
Expand Down
10 changes: 10 additions & 0 deletions test/validationRules/required-fields.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ const requiredFieldsTestCases = {
}
]
},
{
code:
"const x = gql`fragment GreetingOrStoryFragment on GreetingOrStory { ... on Greetings { hello } }`",
errors: [
{
message: `'id' field required on '... on Greetings'`,
type: "TaggedTemplateExpression"
}
]
},
]
};

Expand Down

0 comments on commit 11ef5f3

Please sign in to comment.