• Stars
    star
    2,275
  • Rank 20,247 (Top 0.4 %)
  • Language
    TypeScript
  • License
    MIT License
  • 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

A JavaScript template literal tag that parses GraphQL queries

graphql-tag

npm version Build Status Get on Slack

Helpful utilities for parsing GraphQL queries. Includes:

  • gql A JavaScript template literal tag that parses GraphQL query strings into the standard GraphQL AST.
  • /loader A webpack loader to preprocess queries

graphql-tag uses the reference graphql library under the hood as a peer dependency, so in addition to installing this module, you'll also have to install graphql.

gql

The gql template literal tag can be used to concisely write a GraphQL query that is parsed into a standard GraphQL AST. It is the recommended method for passing queries to Apollo Client. While it is primarily built for Apollo Client, it generates a generic GraphQL AST which can be used by any GraphQL client.

import gql from 'graphql-tag';

const query = gql`
  {
    user(id: 5) {
      firstName
      lastName
    }
  }
`

The above query now contains the following syntax tree.

{
  "kind": "Document",
  "definitions": [
    {
      "kind": "OperationDefinition",
      "operation": "query",
      "name": null,
      "variableDefinitions": null,
      "directives": [],
      "selectionSet": {
        "kind": "SelectionSet",
        "selections": [
          {
            "kind": "Field",
            "alias": null,
            "name": {
              "kind": "Name",
              "value": "user",
              ...
            }
          }
        ]
      }
    }
  ]
}

Fragments

The gql tag can also be used to define reusable fragments, which can easily be added to queries or other fragments.

import gql from 'graphql-tag';

const userFragment = gql`
  fragment User_user on User {
    firstName
    lastName
  }
`

The above userFragment document can be embedded in another document using a template literal placeholder.

const query = gql`
  {
    user(id: 5) {
      ...User_user
    }
  }
  ${userFragment}
`

Note: While it may seem redundant to have to both embed the userFragment variable in the template literal AND spread the ...User_user fragment in the graphQL selection set, this requirement makes static analysis by tools such as eslint-plugin-graphql possible.

Why use this?

GraphQL strings are the right way to write queries in your code, because they can be statically analyzed using tools like eslint-plugin-graphql. However, strings are inconvenient to manipulate, if you are trying to do things like add extra fields, merge multiple queries together, or other interesting stuff.

That's where this package comes in - it lets you write your queries with ES2015 template literals and compile them into an AST with the gql tag.

Caching parse results

This package only has one feature - it caches previous parse results in a simple dictionary. This means that if you call the tag on the same query multiple times, it doesn't waste time parsing it again. It also means you can use === to compare queries to check if they are identical.

Importing graphQL files

To add support for importing .graphql/.gql files, see Webpack loading and preprocessing below.

Given a file MyQuery.graphql

query MyQuery {
  ...
}

If you have configured the webpack graphql-tag/loader, you can import modules containing graphQL queries. The imported value will be the pre-built AST.

import MyQuery from 'query.graphql'

Importing queries by name

You can also import query and fragment documents by name.

query MyQuery1 {
  ...
}

query MyQuery2 {
  ...
}

And in your JavaScript:

import { MyQuery1, MyQuery2 } from 'query.graphql'

Preprocessing queries and fragments

Preprocessing GraphQL queries and fragments into ASTs at build time can greatly improve load times.

Babel preprocessing

GraphQL queries can be compiled at build time using babel-plugin-graphql-tag. Pre-compiling queries decreases script initialization time and reduces bundle sizes by potentially removing the need for graphql-tag at runtime.

TypeScript preprocessing

Try this custom transformer to pre-compile your GraphQL queries in TypeScript: ts-transform-graphql-tag.

React Native and Next.js preprocessing

Preprocessing queries via the webpack loader is not always possible. babel-plugin-import-graphql supports importing graphql files directly into your JavaScript by preprocessing GraphQL queries into ASTs at compile-time.

E.g.:

import myImportedQuery from './productsQuery.graphql'

class ProductsPage extends React.Component {
  ...
}

Webpack loading and preprocessing

Using the included graphql-tag/loader it is possible to maintain query logic that is separate from the rest of your application logic. With the loader configured, imported graphQL files will be converted to AST during the webpack build process.

Example webpack configuration

{
  ...
  loaders: [
    {
      test: /\.(graphql|gql)$/,
      exclude: /node_modules/,
      loader: 'graphql-tag/loader'
    }
  ],
  ...
}

Create React App

Preprocessing GraphQL imports is supported in create-react-app >= v2 using evenchange4/graphql.macro.

For create-react-app < v2, you'll either need to eject or use react-app-rewire-inline-import-graphql-ast.

Testing

Testing environments that don't support Webpack require additional configuration. For Jest use jest-transform-graphql.

Support for fragments

With the webpack loader, you can import fragments by name:

In a file called query.gql:

fragment MyFragment1 on MyType1 {
  ...
}

fragment MyFragment2 on MyType2 {
  ...
}

And in your JavaScript:

import { MyFragment1, MyFragment2 } from 'query.gql'

Note: If your fragment references other fragments, the resulting document will have multiple fragments in it. In this case you must still specify the fragment name when using the fragment. For example, with @apollo/client you would specify the fragmentName option when using the fragment for cache operations.

Warnings

This package will emit a warning if you have multiple fragments of the same name. You can disable this with:

import { disableFragmentWarnings } from 'graphql-tag';

disableFragmentWarnings()

Experimental Fragment Variables

This package exports an experimentalFragmentVariables flag that allows you to use experimental support for parameterized fragments.

You can enable / disable this with:

import { enableExperimentalFragmentVariables, disableExperimentalFragmentVariables } from 'graphql-tag';

Enabling this feature allows you to declare documents of the form.

fragment SomeFragment ($arg: String!) on SomeType {
  someField
}

Resources

You can easily generate and explore a GraphQL AST on astexplorer.net.

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-subscriptions

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

subscriptions-transport-ws

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

apollo-client-devtools

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

apollo-link

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

apollo-link-state

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

apollo-cache-persist

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

fullstack-tutorial

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

eslint-plugin-graphql

🚦 Check your GraphQL query strings against a schema.
JavaScript
1,194
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