• Stars
    star
    1,194
  • Rank 39,182 (Top 0.8 %)
  • Language
    JavaScript
  • Created over 8 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🚦 Check your GraphQL query strings against a schema.

eslint-plugin-graphql

npm version Build Status Get on Slack


[2022-01-25] Note - Upcoming Deprecation Plans: We (Apollo) are working towards fully deprecating this repository. We suggest migrating to the community-supported graphql-eslint. We'll share detailed migration documentation when everything here is ready to be officially deprecated, but just a heads up in case you're planning on adopting anything here for a new project (which you still can of course if this project works for you - support for this project will be minimal however).


An ESLint plugin that checks tagged query strings inside JavaScript, or queries inside .graphql files, against a GraphQL schema.

npm install eslint-plugin-graphql

Screenshot from Atom

eslint-plugin-graphql has built-in settings for four GraphQL clients out of the box:

  1. Apollo client
  2. Relay
  3. Lokka
  4. FraQL

If you want to lint your GraphQL schema, rather than queries, check out cjoudrey/graphql-schema-linter.

Importing schema JSON

You'll need to import your introspection query result or the schema as a string in the Schema Language format. This can be done if you define your ESLint config in a JS file.

Retrieving a remote GraphQL schema

graphql-cli provides a get-schema command (in conjunction with a .graphqlconfig file) that makes retrieving remote schemas very simple.

apollo-codegen also provides an introspect-schema command that can get your remote schemas as well

Common options

All of the rules provided by this plugin have a few options in common. There are examples of how to use these with Apollo, Relay, Lokka, FraQL and literal files further down.

  • env: Import default settings for your GraphQL client. Supported values: 'apollo', 'relay', 'lokka', 'fraql' 'literal'. Defaults to 'apollo'. This is used for the slight parsing differences in the GraphQL syntax between Apollo, Relay, Lokka and FraQL as well as giving nice defaults to some other options.

  • tagName: The name of the template literal tag that this plugin should look for when searching for GraphQL queries. It has different defaults depending on the env option:

    • 'relay': 'Relay.QL'
    • 'internal': Special automatic value
    • others: 'gql', 'graphql'

You also have to specify a schema. You can either do it using one of these options:

  • schemaJson: Your schema as JSON.
  • schemaJsonFilepath: The absolute path to your schema as a .json file. (Warning: this variant is incompatible with eslint --cache.)
  • schemaString: Your schema in the Schema Language format as a string.

Alternatively, you can use a .graphqlconfig file instead of the above three options. If you do there's one more option to know about:

  • projectName: In case you specify multiple schemas in your .graphqlconfig file, choose which one to use by providing the project name here as a string.

There's an example on how to use a .graphqlconfig file further down.

Identity template literal tag

This plugin relies on GraphQL queries being prefixed with a special tag. In Relay and Apollo this is done often, but some other clients take query strings without a tag. In this case, fake-tag can be used to define an identity tag that doesn't do anything except for tell the linter this is a GraphQL query:

import gql from "fake-tag";

const QUERY_VIEWER_NAME = gql`
  query ViewerName {
    viewer {
      name
    }
  }
`;

Fake tags won’t be necessary once /* GraphQL */ comment tags are supported.

GraphQL literal files

This plugin also lints GraphQL literal files ending on .gql or .graphql. In order to do so set env to 'literal' in your .eslintrc.js and tell eslint to check these files as well.

eslint . --ext .js --ext .gql --ext .graphql

Example config for Apollo

// In a file called .eslintrc.js
module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      // Import default settings for your GraphQL client. Supported values:
      // 'apollo', 'relay', 'lokka', 'fraql', 'literal'
      env: 'apollo',

      // Import your schema JSON here
      schemaJson: require('./schema.json'),

      // OR provide absolute path to your schema JSON (but not if using `eslint --cache`!)
      // schemaJsonFilepath: path.resolve(__dirname, './schema.json'),

      // OR provide the schema in the Schema Language format
      // schemaString: printSchema(schema),

      // tagName is gql by default
    }]
  },
  plugins: [
    'graphql'
  ]
}

Example config for Relay

// In a file called .eslintrc.js
module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      // Import default settings for your GraphQL client. Supported values:
      // 'apollo', 'relay', 'lokka', 'fraql', 'literal'
      env: 'relay',

      // Import your schema JSON here
      schemaJson: require('./schema.json'),

      // OR provide absolute path to your schema JSON (but not if using `eslint --cache`!)
      // schemaJsonFilepath: path.resolve(__dirname, './schema.json'),

      // OR provide the schema in the Schema Language format
      // schemaString: printSchema(schema),

      // tagName is set for you to Relay.QL
    }]
  },
  plugins: [
    'graphql'
  ]
}

Example config for Lokka

// In a file called .eslintrc.js
module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      // Import default settings for your GraphQL client. Supported values:
      // 'apollo', 'relay', 'lokka', 'fraql', 'literal'
      env: 'lokka',

      // Import your schema JSON here
      schemaJson: require('./schema.json'),

      // OR provide absolute path to your schema JSON (but not if using `eslint --cache`!)
      // schemaJsonFilepath: path.resolve(__dirname, './schema.json'),

      // OR provide the schema in the Schema Language format
      // schemaString: printSchema(schema),

      // Optional, the name of the template tag, defaults to 'gql'
      tagName: 'gql'
    }]
  },
  plugins: [
    'graphql'
  ]
}

Example config for FraQL

// In a file called .eslintrc.js
module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      // Import default settings for your GraphQL client. Supported values:
      // 'apollo', 'relay', 'lokka', 'fraql', 'literal'
      env: 'fraql',

      // Import your schema JSON here
      schemaJson: require('./schema.json'),

      // OR provide absolute path to your schema JSON
      // schemaJsonFilepath: path.resolve(__dirname, './schema.json'),

      // OR provide the schema in the Schema Language format
      // schemaString: printSchema(schema),

      // Optional, the name of the template tag, defaults to 'gql'
      tagName: 'gql'
    }]
  },
  plugins: [
    'graphql'
  ]
}

Example config for literal graphql files

// In a file called .eslintrc.js
module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      // Import default settings for your GraphQL client. Supported values:
      // 'apollo', 'relay', 'lokka', 'fraql', 'literal'
      env: 'literal',

      // Import your schema JSON here
      schemaJson: require('./schema.json'),

      // OR provide absolute path to your schema JSON (but not if using `eslint --cache`!)
      // schemaJsonFilepath: path.resolve(__dirname, './schema.json'),

      // OR provide the schema in the Schema Language format
      // schemaString: printSchema(schema),

      // tagName is set automatically
    }]
  },
  plugins: [
    'graphql'
  ]
}

Additional Schemas or Tags

This plugin can be used to validate against multiple schemas by identifying them with different tags. This is useful for applications interacting with multiple GraphQL systems. Additional schemas can simply be appended to the options list:

module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      env: 'apollo',
      tagName: 'FirstGQL',
      schemaJson: require('./schema-first.json')
    }, {
      env: 'relay',
      tagName: 'SecondGQL',
      schemaJson: require('./schema-second.json')
    }]
  },
  plugins: [
    'graphql'
  ]
}

Example config when using .graphqlconfig

If you have .graphqlconfig file in the root of your repo you can omit schema-related properties (schemaJson, schemaJsonFilepath and schemaString) from rule config.

// In a file called .eslintrc.js
module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      // Import default settings for your GraphQL client. Supported values:
      // 'apollo', 'relay', 'lokka', 'fraql', 'literal'
      env: 'literal'
      // no need to specify schema here, it will be automatically determined using .graphqlconfig
    }]
  },
  plugins: [
    'graphql'
  ]
}

In case you use additional schemas, specify projectName from .graphqlconfig for each tagName:

module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      env: 'apollo',
      tagName: 'FirstGQL',
      projectName: 'FirstGQLProject'
    }, {
      env: 'relay',
      tagName: 'SecondGQL',
      projectName: 'SecondGQLProject'
    }]
  },
  plugins: [
    'graphql'
  ]
}

Selecting Validation Rules

GraphQL validation rules can be configured in the eslint rule configuration using the validators option. The default selection depends on the env setting. If no env is specified, all rules are enabled by default.

The validators setting can be set either to a list of specific validator names or to the special value "all".

module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      env: 'apollo',
      validators: 'all',
      tagName: 'FirstGQL',
      schemaJson: require('./schema-first.json')
    }, {
      validators: ['FieldsOnCorrectType'],
      tagName: 'SecondGQL',
      schemaJson: require('./schema-second.json')
    }]
  },
  plugins: [
    'graphql'
  ]
}

The full list of available validators is:

  • ExecutableDefinitions
  • FieldsOnCorrectType
  • FragmentsOnCompositeTypes
  • KnownArgumentNames
  • KnownDirectives (disabled by default in relay)
  • KnownFragmentNames (disabled by default in all envs)
  • KnownTypeNames
  • LoneAnonymousOperation
  • NoFragmentCycles
  • NoUndefinedVariables (disabled by default in relay)
  • NoUnusedFragments (disabled by default in all envs)
  • NoUnusedVariables
  • OverlappingFieldsCanBeMerged
  • PossibleFragmentSpreads
  • ProvidedRequiredArguments (disabled by default in relay)
  • ScalarLeafs (disabled by default in relay)
  • SingleFieldSubscriptions
  • UniqueArgumentNames
  • UniqueDirectivesPerLocation
  • UniqueFragmentNames
  • UniqueInputFieldNames
  • UniqueOperationNames
  • UniqueVariableNames
  • ValuesOfCorrectType
  • VariablesAreInputTypes
  • VariablesDefaultValueAllowed
  • VariablesInAllowedPosition

Named Operations Validation Rule

The Named Operation rule validates that all operations are named. Naming operations is valuable for including in server-side logs and debugging.

Pass

query FetchUsername {
  viewer {
    name
  }
}

Fail

query {
  viewer {
    name
  }
}

The rule is defined as graphql/named-operations.

// In a file called .eslintrc.js
module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      env: 'apollo',
      schemaJson: require('./schema.json'),
    }],
    "graphql/named-operations": ['warn', {
      schemaJson: require('./schema.json'),
    }],
  },
  plugins: [
    'graphql'
  ]
}

Required Fields Validation Rule

The Required Fields rule validates that any specified required field is part of the query, but only if that field is available in schema. This is useful to ensure that query results are cached properly in the client.

Pass

// 'uuid' required and present in the schema

schema {
  query {
    viewer {
      name
      uuid
    }
  }
}

query ViewerName {
  viewer {
    name
    uuid
  }
}

Pass

// 'uuid' usually required but not present in the schema here

schema {
  query {
    viewer {
      name
    }
  }
}

query ViewerName {
  viewer {
    name
  }
}

Fail

// 'uuid' required and present in the schema

schema {
  query {
    viewer {
      uuid
      name
    }
  }
}

query ViewerName {
  viewer {
    name
  }
}

The rule is defined as graphql/required-fields and requires the requiredFields option.

// In a file called .eslintrc.js
module.exports = {
  rules: {
    'graphql/required-fields': [
      'error',
      {
        env: 'apollo',
        schemaJsonFilepath: path.resolve(__dirname, './schema.json'),
        requiredFields: ['uuid'],
      },
    ],
  },
  plugins: [
    'graphql'
  ]
}

Capitalization of a first letter of a Type name

This rule enforces that first letter of types is capitalized

Pass

query {
  someUnion {
    ... on SomeType {
      someField
    }
  }
}

Fail

query {
  someUnion {
    ... on someType {
      someField
    }
  }
}

The rule is defined as graphql/capitalized-type-name.

// In a file called .eslintrc.js
module.exports = {
  parser: "babel-eslint",
  rules: {
    "graphql/template-strings": ['error', {
      env: 'apollo',
      schemaJson: require('./schema.json'),
    }],
    "graphql/capitalized-type-name": ['warn', {
      schemaJson: require('./schema.json'),
    }],
  },
  plugins: [
    'graphql'
  ]
}

No Deprecated Fields Validation Rule

The No Deprecated Fields rule validates that no deprecated fields are part of the query. This is useful to discover fields that have been marked as deprecated and shouldn't be used.

Fail

// 'id' requested and marked as deprecated in the schema

schema {
  query {
    viewer {
      id: Int @deprecated(reason: "Use the 'uuid' field instead")
      uuid: String
    }
  }
}

query ViewerName {
  viewer {
    id
  }
}

The rule is defined as graphql/no-deprecated-fields.

// In a file called .eslintrc.js
module.exports = {
  rules: {
    'graphql/no-deprecated-fields': [
      'error',
      {
        env: 'relay',
        schemaJson: require('./schema.json')
      },
    ],
  },
  plugins: [
    'graphql'
  ]
}

More Repositories

1

apollo-client

🚀  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
TypeScript
19,300
star
2

apollo-server

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
TypeScript
13,522
star
3

react-apollo

♻️ React integration for Apollo Client
JavaScript
6,887
star
4

apollo-ios

📱  A strongly-typed, caching GraphQL client for iOS, written in Swift.
Swift
3,737
star
5

apollo-kotlin

🤖  A strongly-typed, caching GraphQL client for the JVM, Android, and Kotlin multiplatform.
Kotlin
3,382
star
6

apollo-tooling

✏️ Apollo CLI for client tooling (Mostly replaced by Rover)
TypeScript
3,042
star
7

apollo

🚀 Open source tools for GraphQL. Central repo for discussion.
JavaScript
2,626
star
8

graphql-tag

A JavaScript template literal tag that parses GraphQL queries
TypeScript
2,275
star
9

graphql-subscriptions

📰 A small module that implements GraphQL subscriptions for Node.js
TypeScript
1,567
star
10

subscriptions-transport-ws

🔃 A WebSocket client + server for GraphQL subscriptions
TypeScript
1,524
star
11

apollo-client-devtools

Apollo Client browser developer tools.
TypeScript
1,481
star
12

apollo-link

🔗 Interface for fetching and modifying control flow of GraphQL requests
TypeScript
1,438
star
13

apollo-link-state

✨ Manage your application's state with Apollo!
TypeScript
1,405
star
14

apollo-cache-persist

🎏 Simple persistence for all Apollo Cache implementations
TypeScript
1,368
star
15

fullstack-tutorial

🚀 The Apollo platform tutorial app
TypeScript
1,233
star
16

router

A configurable, high-performance routing runtime for Apollo Federation 🚀
Rust
793
star
17

apollo-link-rest

Use existing REST endpoints with GraphQL
TypeScript
783
star
18

federation

🌐  Build and scale a single data graph across multiple services with Apollo's federation gateway.
TypeScript
659
star
19

apollo-fetch

🐶 Lightweight GraphQL client that supports middleware and afterware
TypeScript
576
star
20

apollo-rs

Spec compliant GraphQL Tools in Rust.
Rust
566
star
21

reason-apollo

Reason binding for Apollo Client and React Apollo
Reason
552
star
22

federation-demo

Federation 2 supersedes this demo and this example is no longer the newest. See https://www.apollographql.com/docs/federation/ for migration steps!
JavaScript
502
star
23

ac3-state-management-examples

✨ Learn Apollo Client 3's state management best practices
TypeScript
493
star
24

apollo-tracing

A GraphQL extension for performance tracing
475
star
25

apollo-client-nextjs

Apollo Client support for the Next.js App Router
TypeScript
446
star
26

persistgraphql

A build tool for GraphQL projects.
TypeScript
424
star
27

rover

The CLI for Apollo GraphOS
Rust
404
star
28

gatsby-theme-apollo

💜 Themes that we use to build Gatsby sites at Apollo
JavaScript
371
star
29

apollo-link-persisted-queries

Persisted Query support with Apollo Link
TypeScript
307
star
30

xcode-graphql

🛠 Xcode add-ons that add syntax highlighting for GraphQL query document files
Shell
276
star
31

apollo-studio-community

🎡  GraphQL developer portal featuring an IDE (Apollo Explorer), auto-documentation, metrics reporting, and more. This repo is for issues, feature requests, and preview docs. 📬
249
star
32

federation-jvm

JVM support for Apollo Federation
Java
247
star
33

supergraph-demo-fed2

🍿 Supergraph demo for Federation 2 and Apollo Router
Shell
162
star
34

principled-graphql

📈 Best practices for implementing and scaling a data graph
JavaScript
148
star
35

apollo-cache-control

A GraphQL extension for cache control
146
star
36

supergraph-demo

🍿 Compose subgraphs into a Federation v1 supergraph at build-time with static composition to power a federated graph router at runtime.
Shell
135
star
37

apollo-feature-requests

🧑‍🚀 Apollo Client Feature Requests | (no 🐛 please).
130
star
38

spotify-showcase

A Spotify clone that showcases the Apollo GraphQL platform.
TypeScript
126
star
39

meteor-integration

🚀 meteor add apollo
JavaScript
108
star
40

frontpage-ios-app

📄 Apollo "hello world" app, for iOS
Swift
101
star
41

space-kit

👩‍🚀 Home base for Apollo's design system: https://space-kit.netlify.com
TypeScript
88
star
42

apollo-scalajs

Use Apollo GraphQL from Scala.js apps!
Scala
88
star
43

invariant-packages

Packages for working with invariant(condition, message) assertions
TypeScript
88
star
44

apollo-federation-subgraph-compatibility

A repo to test subgraph libraries compatibility with the Apollo Federation Specification
TypeScript
77
star
45

starwars-server

JavaScript
73
star
46

blog

📝 Blog website built with Wordpress and Gatsby
JavaScript
68
star
47

iOSTutorial

The tutorial application for the Apollo iOS SDK
Swift
68
star
48

odyssey-lift-off-part1

JavaScript
64
star
49

federation-jvm-spring-example

Apollo Federation JVM example implementation using Spring for GraphQL
Java
64
star
50

vscode-graphql

Apollo GraphQL VS Code extension
TypeScript
55
star
51

apollo-kotlin-tutorial

The code for the Apollo Kotlin Tutorial
Kotlin
52
star
52

docs-examples

Example code supporting the Apollo docs
TypeScript
50
star
53

docs

📚 Apollo's docs framework
MDX
42
star
54

apollo-kotlin-2-tutorial

The code for the Apollo Android Tutorial
Kotlin
38
star
55

iOSCodegenTemplate

A template for the code you need to set up to get Swift Scripting up and running.
Swift
38
star
56

datasource-rest

A caching data source for REST APIs
TypeScript
37
star
57

apollo-workbench-vscode

Apollo Workbench is a design tool that facilitates planning changes to your supergraph. It enables you to understand the overall composition and execution of any given query at design time.
TypeScript
37
star
58

apollo-utils

Monorepo of common utilities related to Apollo and GraphQL
TypeScript
35
star
59

graphql-testing-library

Testing utilities that encourage good practices for apps built with GraphQL.
TypeScript
35
star
60

federation-rs

Contains source code for Apollo Federation's Rust<--> JavaScript interop
Rust
34
star
61

react-apollo-error-template

Apollo Client issue reproduction.
JavaScript
33
star
62

embeddable-explorer

TypeScript
32
star
63

federation-migration-example

🚀Example app migrated from schema stitching to Apollo federation
JavaScript
32
star
64

odyssey-lift-off-part5-server

Odyssey Lift-off V - Server - Course Companion App
JavaScript
31
star
65

odyssey-lift-off-part5-client

Odyssey Lift-off V - Client - Course Companion App
JavaScript
28
star
66

GraphiQL-Subscriptions-Fetcher

GraphiQL's fetcher that supports GraphQL-Subscriptions with the `subscriptions-transport-ws` package
TypeScript
28
star
67

supergraph-demo-k8s-graph-ops

Archived: GitOps config repo for an Apollo GraphQL federated graph with a supergraph router and subgraph services deployed to Kubernetes.
Shell
28
star
68

apollo-ios-dev

Apollo iOS Development Repo
Swift
28
star
69

apollo-ios-pagination

Swift
26
star
70

odyssey-lift-off-part2

Odyssey Lift-off Part 2 Course Companion App
JavaScript
26
star
71

spacex

A re-creation of https://github.com/SpaceXLand/api
TypeScript
21
star
72

apollo-graphql-stream-scenes

This is used for hosting streaming scenes for OBS - for Apollo GraphQL stream
JavaScript
19
star
73

federation-next

Moved to the Router repository
Rust
19
star
74

subgraph-template-typescript-apollo-server-boilerplate

A template for a minimal setup Apollo Server 4.x using TypeScript
TypeScript
17
star
75

federation-hotchocolate

HotChocolate support for Apollo Federation
C#
16
star
76

odyssey-lift-off-part3

Odyssey Lift-off Part 3 Course Companion App
JavaScript
15
star
77

odyssey-voyage-I

JavaScript
14
star
78

typescript-repo-template

A template for TypeScript projects with pre-configured tooling
TypeScript
14
star
79

subgraph-template-typescript-apollo-server

A Typescript template for Apollo Server as a subgraph using Apollo Federation
TypeScript
13
star
80

next-apollo-example

Template for creating Apollo Client + Next.js reproductions
JavaScript
13
star
81

community

Apollo community guidelines
JavaScript
13
star
82

design-principles

Where we are defining and collaborating on our Apollo internal design principles (individually and collaboratively). This is a public repo, but intended only for use by Apollo employees.
13
star
83

odyssey-lift-off-part4

Odyssey Lift-off Part 4 Course Companion App
JavaScript
12
star
84

core-schema-js

Typescript library for processing core schemas
TypeScript
12
star
85

apollo-client-swift-playground

Swift
11
star
86

apollo-ios-codegen

Apollo iOS Code Generation
Swift
11
star
87

test-span

Rust
11
star
88

specs

Apollo Library of Technical Specifications
CSS
10
star
89

router-template

A general purpose self-hosted Apollo Router template connected to GraphOS
Dockerfile
10
star
90

apollo-midnight

A VS Code color theme based on Apollo Studio Explorer color palette.
9
star
91

serde_json_bytes

a JSON Value object with strings backed by Bytes, parsed by serde_json
Rust
8
star
92

hack-the-supergraph

JavaScript
8
star
93

subgraph-template-rust-async-graphql

A boilerplate template project for building a subgraph with async-graphql
Rust
8
star
94

router-biscuit-plugin

⚠️experimental⚠️ plugin for the router using Biscuit tokens for authorization
Rust
7
star
95

devhub

🔭 Explore all the latest resources for building apps with Apollo
JavaScript
7
star
96

client-router-e2e-tests

Apollo Client ↔️ Router E2E Test Suite
JavaScript
7
star
97

odyssey-lift-off-lab

Odyssey Lift-off Lab starter repo
JavaScript
7
star
98

graphchat

TypeScript
6
star
99

introspector-gadget

GraphQL introspection utilities
Rust
6
star
100

zen-observable-ts

Thin wrapper around zen-observable and @types/zen-observable, to support ESM exports
JavaScript
6
star