GraphQL-ESLint

repository·master·Indexed 21 days ago

https://github.com/graphql-hive/graphql-eslint

An ESLint plugin for linting GraphQL code, supporting standalone .graphql files and GraphQL template literals in JavaScript or TypeScript. It provides a comprehensive set of rules for schema and operation design, including alphabetization, naming conventions, and description styles. The plugin includes a parser, processor, and predefined configuration sets compatible with both legacy and Flat Config formats.

Tokens
48.1K
Snippets
168
Records
219
Agent score
71%

What's inside GraphQL-ESLint

  1. What is GraphQL-ESLint?

    master

    GraphQL-ESLint is a tool that integrates GraphQL with ESLint to improve the developer experience. It allows you to lint both GraphQL schemas and GraphQL operations (queries, mutations, etc.) using the ESLint engine. It works by acting as an ESTree parser within the ESLint ecosystem.

    Key capabilities include:

    • Multi-format support: Lints .graphql files, gql template literal usages, and /* GraphQL */ magic comments.
    • Comprehensive linting: Validates, lints, and prettifies GraphQL schemas and operations, checking for best practices.
    • Advanced Type Information: Provides extended type info for complex linting rules.
    • Extensibility: Supports custom rules built on GraphQL's AST and the ESLint API.
    • IDE Integration: Visualizes linting issues directly in popular IDEs like VSCode and WebStorm.
    • Standard Tooling Support: Integrates with ESLint directives (e.g., eslint-disable-next-line) and GraphQL Config.
  2. Understand GraphQL-ESLint rule metadata and icons

    master

    When browsing the list of available GraphQL-ESLint rules, you can identify their behavior and applicability using specific icons:

    • Target Scope:
      • 📄: The rule applies to schema documents.
      • 📦: The rule applies to operations.
    • Rule Implementation:
      • 🚀: This is a native graphql-eslint rule.
      • 🔮: This is a graphql-js rule.
    • Fixability:
      • 🔧: Some problems reported by the rule are automatically fixable using the ESLint --fix command line option.
      • 💡: Some problems reported by the rule are manually fixable via editor suggestions.
  3. Access GraphQL Schema and TypeInfo in rules

    master

    If a GraphQL schema is provided in your ESLint configuration, you can access it within your rules in two ways:

    1. Accessing the GraphQLSchema object

    To ensure your rule has access to the schema, call requireGraphQLSchema(ruleName, context). This will return the loaded schema or throw an error if the schema is missing.

    2. Accessing TypeInfo via .typeInfo()

    Every visited node has a .typeInfo() method. This method returns an object containing type information relevant to that specific node (e.g., the GraphQLOutputType for a SelectionSet). If no schema is loaded, .typeInfo() returns undefined.

    Note: If your rule depends on type information, you must call requireGraphQLSchema to validate that the schema is available.

    import { requireGraphQLSchema } from '@graphql-eslint/eslint-plugin'
    
    export const rule = {
      create(context) {
        requireGraphQLSchema('my-rule', context)
    
        return {
          SelectionSet(node) {
            const typeInfo = node.typeInfo()
            if (typeInfo.gqlType) {
              console.log(`The GraphQLOutputType is: ${typeInfo.gqlType}`)
            }
          }
        }
      }
    }
  4. How the parser converts GraphQL AST to ESTree

    master

    To make the GraphQL AST compatible with the ESTree format used by ESLint, the parser performs several transformations:

    • Type Mapping: It maps the GraphQL kind field to an ESTree-compatible type field.
    • Field Renaming: To avoid conflicts with the new type field, any existing GraphQL AST nodes that used a type field have that field renamed to gqlType.
    • Circular Reference Removal: It removes circular JSON links (specifically around GraphQL Location and the Lexer) to prevent stack overflow errors during ESTree processing.
    • Location Normalization: It transforms the GraphQL location field into a structure compatible with ESTree's location format.
  5. How the GraphQL-ESLint parser works

    master

    The graphql-eslint parser follows a multi-step lifecycle to transform GraphQL code into a format ESLint can analyze:

    1. Loading: It loads GraphQL code via ESLint core (from .graphql files) or via an ESLint processor for code embedded in other file types.
    2. Parsing: It uses graphql-js and graphql-tools to parse the code into a DocumentNode.
    3. Comment Extraction: It extracts comments (starting with #) from the AST to provide directive hints to ESLint.
    4. Schema Loading: If a schema is provided or graphql-config is detected, the schema is loaded and made available to rules via parserServices.
    5. ESTree Conversion: The DocumentNode is converted into an ESTree-compatible structure. If a schema was loaded, nodes are enriched with typeInfo.
  6. Use the `@graphql-eslint/executable-definitions` rule

    master

    The @graphql-eslint/executable-definitions rule ensures that a GraphQL document is valid for execution by verifying that all definitions within the document are either operation or fragment definitions. This rule is a wrapper around the graphql-js validation function.

    Requirements

    • Requires GraphQL Schema: true. You must provide a GraphQL schema for this rule to function.
    • Requires GraphQL Operations: false.

    Enabling the rule

    You can enable this rule by extending the recommended operations configuration in your ESLint configuration file:

    {
      "extends": "plugin:@graphql-eslint/operations-recommended"
    }
  7. Use the `@graphql-eslint/no-undefined-variables` rule

    master

    The @graphql-eslint/no-undefined-variables rule ensures that every variable used in a GraphQL operation (including those inside fragment spreads) is explicitly defined in the operation's variable definitions. This rule acts as a wrapper around the graphql-js validation function.

    Requirements

    • GraphQL Schema: This rule requires access to a GraphQL schema to validate operations.
    • GraphQL Operations: This rule requires GraphQL operations to be present in the files being linted.

    Enabling the rule

    You can enable this rule by extending the recommended operations configuration in your ESLint configuration file:

    {
      "extends": ["plugin:@graphql-eslint/operations-recommended"]
    }
  8. Use the `@graphql-eslint/unique-type-names` rule

    master

    The @graphql-eslint/unique-type-names rule ensures that a GraphQL document is valid by verifying that all defined types have unique names. This rule is a wrapper around the graphql-js validation function.

    To enable this rule, include the following property in your ESLint configuration file:

    "extends": ["plugin:@graphql-eslint/schema-recommended"]
  9. Use GraphQL-ESLint with `.svelte` files

    master

    To lint GraphQL inside .svelte files, you must configure ESLint to recognize the .svelte file extension and ensure your GraphQL parser/plugin is applied to those files. This typically involves using eslint-plugin-svelte alongside @graphql-eslint/eslint-plugin and configuring the overrides section in your ESLint configuration to target .svelte files.

    // Example configuration pattern for Svelte files
    module.exports = {
      overrides: [
        {
          files: ['*.svelte'],
          extends: ['plugin:@graphql-eslint/plugin'],
          // Additional Svelte-specific configuration
        }
      ]
    };