Skip to content
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

Custom rule breaks NoUnusedVariablesRule #3889

Open
alanchristensen opened this issue Apr 26, 2023 · 1 comment
Open

Custom rule breaks NoUnusedVariablesRule #3889

alanchristensen opened this issue Apr 26, 2023 · 1 comment

Comments

@alanchristensen
Copy link

I created a rule that visits a fragment's selectionSet when it encounters a FRAGMENT_SPREAD. The rule itself worked as desired, however doing so caused NoUnusedVariablesRule to fail if a variable was used in a fragment spread. It appears that my custom rule is changing the visitor in the default rules.

Here's a slimmed down version of my code that demonstrates the problem:

import { buildSchema, parse, validate, NoUnusedVariablesRule, Kind, ValidationContext, ASTVisitor } from 'graphql';

function CustomRule(context: ValidationContext): ASTVisitor {
  return {
    enter: (node) => {
      // If FRAGMENT_SPREAD, then return the selectionSet of the fragment definition
      // This causes visitor to visit the selectionSet instead of ending on the current node
      if (node.kind === Kind.FRAGMENT_SPREAD) {
        return context.getFragment(node.name.value)?.selectionSet;
      }

      return undefined;
    },
    leave: () => {},
  };
}

const schema = buildSchema(/* GraphQL */ `
  type Author {
    name: String
  }
  type Query {
    author: Author
  }
`);

const doc = parse(/* GraphQL */ `
  query AUTHOR($s: Boolean = false) {
    author {
      ...FRAG @skip(if: $s)
    }
  }

  fragment FRAG on Author {
    name
  }
`);

console.debug(validate(schema, doc, [NoUnusedVariablesRule, CustomRule]));

This causes a GraphQLError: Variable "$s" is never used in operation "AUTHOR". error. If you remove the CustomRule then no errors are reported.

@IvanGoncharov
Copy link
Member

@alanchristensen Wow, this is unexpected behavior.
I will take a look, at what is happening here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants
@alanchristensen @IvanGoncharov and others