• Stars
    star
    674
  • Rank 64,735 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated 10 months ago

Reviews

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

Repository Details

TypeScript Language Service Plugin for GraphQL developers

ts-graphql-plugin

github actions codecov npm version deps GitHub license

Provides functions to help TypeScript GraphQL client development including auto completion, query validation, type generation and so on.

capture

This plugin has the following features:

  • As TypeScript Language Service extension:
    • Completion suggestion
    • Get GraphQL diagnostics
    • Display GraphQL quick info within tooltip
  • As CLI
    • Generate ts type files from your GraphQL operations in your TypeScript sources
    • Extract or validate GraphQL operations in your TypeScript sources
  • As webpack plugin
    • Transform your queries to GraphQL AST object statically

ToC

Getting started

First, confirm that your project has TypeScript and graphql(v15.x.0 or later).

To install this plugin, execute the following:

npm install ts-graphql-plugin -D

And configure plugins section in your tsconfig.json, for example:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "plugins": [
      {
        "name": "ts-graphql-plugin",
        "schema": "path-or-url-to-your-schema.graphql",
        "tag": "gql"
      }
    ]
  }
}

It's ready to go. Launch your TypeScript IDE.

CLI Usage

$ npx ts-graphql-plugin <command> [options]

If you install this plugin, a short alias tsgql is also available instead of ts-graphql-plugin.

Available commands are typegen, extract, validate and report. If you want more detail, runts-graphql-plugin --helports-graphql-plugin <command> --help in your console.

typegen command

Generate TypeScript types from GraphQL operations or fragments in your .ts source files. Here is an output example.

extract command

Extracts GraphQL operations and fragments from ts files and writes them to manifest.json.

validate command

Validates your GraphQL operations and fragments in your ts files and report syntax or semantic errors.

report command

Extracts GraphQL operations and fragments from ts files and report them to a Markdown file. Here is an output example.

Plugin options

Pass plugin options to your tsconfig.json to configure this plugin.

/* tsconfig.json */
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "ts-graphql-plugin",
        /* plugin options */
        "schema": "path-or-url-to-your-schema.graphql",
        "tag": "gql",
        ...
      }
    ]
  }
}

schema

It's a required parameter and should point your GraphQL schema SDL file such as :

type Author {
  id: ID!
  firstName: String
  lastName: String
  posts: [Post]
}
type Post {
  id: ID!
  title: String
  author: Author
  votes: Int
}
type Query {
  posts: [Post]
  author(id: ID!): Author
}

Also you can use GraphQL introspection query result data such as:

{
  "__schema": {
    "queryType": {
      "name": "Query"
    },
    "types": [
      {
        "kind": "OBJECT",
        "name": "Query",
        "description": null,
        "fields": [
          {
            "name": "viewer",
            :

You can pass URL and custom HTTP headers. It's useful to use an existing GraphQL server like GitHub v4 API. For example:

  "schema": {
    "http": {
      "url": "https://api.github.com/graphql",
      "headers": {
        "Authorization": "Bearer YOUR_GITHUB_API_TOKEN"
      }
    }
  },

If you need to use more complex logic like fetch bearer token using client secret then you can build your http schema configuration using javascript. First, you need to setup your plugin configuration like below:

  "schema": {
    "http": {
      "fromScript": "my-graphql-config.js"
    }
  },

Your script have to return valid RequestSetup or Promise<RequestSetup> object:

url: string;
method?: string; // default to 'POST'
headers?: { [key: string]: string };

Example how configuration script may look like:

// my-graphql-config.js
const fetch = require('node-fetch');

module.exports = projectRootPath =>
  new Promise(resolve => {
    fetch('http://localhost/identity-server/connect/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `client_secret=${process.env.MY_CLIENT_SECRET}`,
    })
      .then(response => response.json())
      .then(response => {
        resolve({
          url: 'http://localhost/graphql',
          method: 'POST', // unnecessary, "POST" is default value
          headers: {
            Authorization: `Bearer ${response.access_token}`,
          },
        });
      });
  });

The schema option accepts the following type:

type SchemaConfig =
  | string
  | {
      file: {
        path: string;
      };
    }
  | {
      http: {
        url: string;
        method?: string;
        headers?: { [key: string]: string };
      };
    }
  | {
      http: {
        fromScript: string;
      };
    };

tag

It's optional. When it's set, this plugin works only if the target template string is tagged by a function whose name is equal to this parameter.

If not set, this plugin treats all template strings in your .ts as GraphQL query.

For example:

import gql from 'graphql-tag';

// when tag paramter is 'gql'
const str1 = gql`query { }`; // work
const str2 = `<div></div>`; // don't work
const str3 = otherTagFn`foooo`; // don't work

It's useful to write multiple kinds template strings(e.g. one is Angular Component template, another is Apollo GraphQL query).

localSchemaExtensions

It's optional. If you want to extend server-side schema, derived from schema option, you can set path of SDL file of your local extension.

For example:

# local-extension.graphql

directive @client on FIELD

type SomeClientOnlyType {
  name: String!
}

extend type Query {
  someLocalField: SomeClientOnlyType!
}
/* tsconfig.json */
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "ts-graphql-plugin",
        "schema": "base-schema.graphql",
        "localSchemaExtensions": ["local-extension.graphql"]
      }
    ]
  }
}

The above example setting allows to write the following query:

const query = gql`
  query {
    someLocalField @client {
      name
    }
  }
`;

typegen.addons

It's optional. You can extend CLI's typegen command with this option.

For example, the following configuration loads my-addon.ts, which is an Addon to map URL custom GraphQL scalar field to TypeScript string type.

/* tsconfig.json */
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "ts-graphql-plugin",
        "schema": "schema.graphql",
        "typegen": {
          "addons": [
            "./my-addon"
          ]
        }
      }
    ]
  }
}
/* my-addon.ts */

import ts from 'typescript';
import { TypeGenAddonFactory } from 'ts-graphql-plguin';

const addonFactory: TypeGenAddonFactory = () => ({
  customScalar({ scalarType }) {
    if (scalarType.name === 'URL') {
      return ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);
    }
  },
});

module.exports = addonFactory;

The addons property accepts an array of strings. And each string should point Node.js module which implements TypeGenAddonFactory interface. You can pass not only ".js" files but also ".ts" files.

If you learn how to create your Addon, see type generator customization guide for more details.

ts-graphql-plugin also provides built-in Addons. See also the Built-in Type Generator Addons section.

removeDuplicatedFragments

It's optional and default: true. By default, this plugin ignores duplicated fragment definitions such as:

const fragment = gql`
  fragment A on Query {
    id
  }
`;

const query = gql`
  ${fragment}
  query MyQuery {
    ...A
  }
  ${fragment}
  # Duplicated fragment interpolation
`;

This option affects all editor supporting functions, results of CLI commands and results of transformation.

If you set this option false, this plugin passes through query document without removing duplication.

Built-in Type Generator Addons

typed-query-document

This Addon requires graphql v15.4.0 or later. To enable this feature, configure as the following:

{
  "compilerOptions": {
    "plugins": [
      {
        "name": "ts-graphql-plugin",
        "tag": "gql",
        "schema": "schema.graphql",
        "typegen": {
          "addons": [
            "ts-graphql-plugin/addons/typed-query-document"
          ]
        }
      }
    ]
  }
}

When enabled generated files export a type based on TypedQueryDocumentNode from GraphQL. The type extends the standard DocumentNode AST type but also includes types for result data and variables as type arguments.

To use this feature you can apply a type assertion to gql template tag expressions that evaluate to a DocumentNode value.

For example:

const query = gql`
  query MyQuery($take: Int!) {
    recipes(take: $take) {
      id
      title
    }
  }
` as import('./__generated__/my-query.ts').MyQueryDocument;

With that type assertion in place result data and variable types will automatically flow through any function that accepts the TypedQueryDocumentNode type.

For example here is how you can write a wrapper for the useQuery function from Apollo Client:

import { gql, QueryHookOptions, QueryResult, useQuery } from '@apollo/client';
import { TypedQueryDocumentNode } from 'graphql';
function useTypedQuery<ResponseData, Variables>(
  query: TypedQueryDocumentNode<ResponseData, Variables>,
  options: QueryHookOptions<ResponseData, Variables>,
): QueryResult<ResponseData, Variables> {
  return useQuery(query, options);
}
// example usage
const { data } = useTypedQuery(query, { variables: { take: 100 } });
//      ^                                          ^
//      inferred type is `MyQuery`                 |
//                                                 |
//                                        inferred type is `MyQueryVariables`

The result is that generated types are associated with queries at the point where the query is defined instead of at the points where the query is executed.

webpack custom transformer

ts-graphql-plugin provides TypeScript custom transformer to static transform from query template strings to GraphQL AST. It's useful if you use https://github.com/apollographql/graphql-tag

/* webpack.config.js */
const TsGraphQLPlugin = require('ts-graphql-plugin/webpack');

const tsgqlPlugin = new TsGraphQLPlugin({
  /* plugin options */
});

module.exports = {
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: 'ts-loader',
        options: {
          getCustomTransformers: () => ({
            before: [
              tsgqlPlugin.getTransformer({
                /* transformer options */
              }),
            ],
          }),
        },
      },
    ],
  },
  plugins: [tsgqlPlugin],
};

NOTE: For now, this plugin transforms nothing when webpack's --mode option is development and webpack runs with --watch option.

webpack plugin options

tsconfigPath optional

Set your project tsconfig json's file path. Default value: tsconfig.json.

Transformer options

removeFragmentDefinitions optional

Default: true. If set, the transformer transforms template strings which include only GraphQL fragment definitions to empty string literal.

For example, we finally does not need the GraphQL AST document of fragment. We need interpolated GraphQL query AST for query. So this transformer statically resolves ${fragment} interpolation and removes right-hand-side of the fragment variable.

const fragment = gql`
  fragment MyFragment on Query {
    hello
  }
`;

const query = gql`
  ${fragment}
  query MyQuery {
    ...MyFragment
  }
`;

documentTransformers optional

Default: []. You can set an array of GraphQL AST document visitor functions. The visitor functions should be compatible to https://graphql.org/graphql-js/language/#visit .

Template strings

This tool analyzes template string literals in .ts files such as:

const query = gql`
  query MyQuery = {
    viewer {
      id
      name
    }
  }
`;

NOTE

This tool cannot interpret queries containing too complex TypeScript expressions because it statically explores GraphQL queries.

/* It's ok */

const fragment = gql`
  fragment MyFragment on User {
    id
    name
  }
`;

const query = gql`
  ${fragment}
  query MyQuery {
    viewer {
      ...MyFragment
    }
  }
`;
/* Bad */

const query = gql`
  query MyQuery {
    ${someComplexFunction()}
  }
`;

Keep your queries static (see also https://blog.apollographql.com/5-benefits-of-static-graphql-queries-b7fa90b0b69a ).

Available editors

I've checked the operation with the following editors:

  • Visual Studio Code
  • Vim (with tsuquyomi)

And the following editor have TypeScript plugin with LanguageService so they're compatible with this plugin:

  • Emacs
  • Sublime text
  • Eclipse

Version compatibility

  • If you use graphql < 15.x, install ts-graphql-plugin@^1.x.x.
  • If you use typescript < 4.8.x, install ts-graphql-plugin@^2.x.x.

Contributing

See contribution guide.

License

This software is released under the MIT License, see LICENSE.txt.

More Repositories

1

tsuquyomi

A Vim plugin for TypeScript
Vim Script
1,384
star
2

typed-css-modules

Creates .d.ts files from CSS Modules .css files
TypeScript
918
star
3

lerna-yarn-workspaces-example

How to build TypeScript mono-repo project with yarn and lerna
TypeScript
893
star
4

electron-connect

Livereload tool for Electron
JavaScript
339
star
5

npm-ts-workspaces-example

Monorepos example project using npm workspaces and TypeScript project references
TypeScript
296
star
6

jest-prisma

Jest environment for integrated testing with Prisma client
TypeScript
245
star
7

typescript-eslint-language-service

TypeScript language service plugin for ESLint
TypeScript
243
star
8

prisma-fabbrica

Prisma generator to define model factory
TypeScript
221
star
9

eslint-plugin-tutorial

A tutorial/template repository to explain how to create your eslint plugins
TypeScript
190
star
10

gql-study-workshop

TypeScript
144
star
11

vim-js-pretty-template

highlights JavaScript's Template Strings in other FileType syntax rule
Vim Script
143
star
12

electron-jsx-babel-boilerplate

Electron boilerplate with React.js and babel
JavaScript
118
star
13

vison

A Vim plugin for writing JSON with JSON Schema
Vim Script
96
star
14

zisui

Yet another CLI to screenshot your Storybook
TypeScript
72
star
15

angular-puppeteer-demo

A demonstration repository explains how to using Puppeteer in unit testing
TypeScript
58
star
16

pico-ml

A toy programming language which is a subset of OCaml.
TypeScript
50
star
17

x-img-diff

Detect structural difference information of 2 images considering into translation
C++
47
star
18

graphql-decorator

TypeScript
43
star
19

apollo-link-fragment-argument

An Apollo Link to enable to parameterize fragments
TypeScript
40
star
20

better-name

CLI tool to move JavaScript(ES2015) or TypeScript module files
TypeScript
34
star
21

type-dungeon

TypeScript code exercise
TypeScript
31
star
22

talt

Template functions to generate TypeScript AST node object
TypeScript
28
star
23

ngx-typed-forms

Extends Angular reactive forms strongly typed
TypeScript
27
star
24

loadable-ts-transformer

TypeScript custom transformer for loadable-components SSR
TypeScript
26
star
25

typescript-css-modules-demo

A working demo of CSS Modules, using TypeScript, css-modulesify and typed-css-modules
TypeScript
25
star
26

angular2-load-children-loader

A webpack loader for ng2 lazy loading
JavaScript
23
star
27

electron-disclosure

Sample electron app
JavaScript
22
star
28

ng2-lazy-load-demo

A sample repository for Angular2 lazy module loading
TypeScript
22
star
29

opencv-wasm-knnmatch-demo

Web Assembly OpenCV Feature Matching Demonstration
JavaScript
21
star
30

ionic-apollo-simple-app

Explains how to develop Ionic application with Apollo GraphQL client
TypeScript
19
star
31

ngx-zombie-compiler

Fast JiT compiler for Angular testing
TypeScript
15
star
32

decode-tiff

⚡ A lightweight JavaScript TIFF decoder 🎨
JavaScript
15
star
33

ts-server-side-anatomy

Explain what TypeScript server(tsserver) does under your editors
TypeScript
15
star
34

tsuquyomi-vue

vim plugin for TypeScript and Vue.js
Vim Script
15
star
35

generator-ngdoc

Yeoman generator for AngularJS's module documentation
JavaScript
14
star
36

ts-playground-plugin-vim

TypeScript Playground plugin for Vim keybindings
TypeScript
12
star
37

prisma-yoga-example

GraphQL server example using Prisma and graphql-yoga
TypeScript
12
star
38

tsc-react-example

Example to compile React JSX with TypeScript
JavaScript
10
star
39

puppeteer-example

JavaScript
10
star
40

angular-recursive

AngularJS directives for recursive data.
JavaScript
9
star
41

nirvana-js

⚡ JavaScript file runner using Electron
TypeScript
9
star
42

dgeni-ngdocs-example

JavaScript
7
star
43

rxdb-simple-chat-app

simple chat application using RxDB
JavaScript
7
star
44

falcor-firebase

It provides a Falcor datasource from your Firebase database
JavaScript
7
star
45

swagger-codegen-customize-sample

A sample repository for customize swagger-codegen
HTML
6
star
46

zakki

6
star
47

falcor-lambda

creates AWS Lambda handler from Falcor's data source
JavaScript
6
star
48

angular-karma-chrome-headless-demo

TypeScript
6
star
49

server-components-with-container-presentation

TypeScript
6
star
50

storycov

TypeScript
5
star
51

prisma2-nexus-example

TypeScript
5
star
52

screenshot-testing-demo-ngjp18

Demonstration repository "Screenshot test with Angular" session ng-japan18
TypeScript
5
star
53

apollo-angular-example

An example repository to explain how to integrate Apollo and Angular
TypeScript
5
star
54

serverless-falcor-starter

A Serverless project including Falcor routing.
JavaScript
5
star
55

vim-dtsm

A Vim plugin to execute TypeScript dtsm command
Vim Script
4
star
56

dotfiles

settings
Vim Script
4
star
57

arlecchino

TypeScript
4
star
58

angular-sss-demo

Storybook, Screenshot, and Snapshot testing for Angular
TypeScript
4
star
59

graphql-script-sample

Shell script GraphQL client for GitHub v4 API sample
Shell
3
star
60

storybook-angular-cli-helper

TypeScript
3
star
61

storyshots-with-portal-repro

JavaScript
3
star
62

simple-coverage-diff-action

TypeScript
3
star
63

fretted-strings

Mark on your strings and get it's position
TypeScript
3
star
64

face_of_the_year

Python
3
star
65

vim-json-schema-nav

Vim Script
3
star
66

apollo-sandbox

TypeScript
2
star
67

ts-react-css-modules-example

A sample repository for React JSX with CSS Modules for TypeScript
TypeScript
2
star
68

graphql-streaming-example

GraphQL @defer/@stream example
TypeScript
2
star
69

tsjp-resources

TypeScript
2
star
70

karma-nightmare-angular-demo

A working demonstration for visual regression testing of Angular application.
TypeScript
2
star
71

react-apollo-ssr-demo

TypeScript
2
star
72

eslint-plugin-unlearned-kanji

TypeScript
2
star
73

react-css-note

HTML
2
star
74

inspectorium

Inspect your GitHub source code
TypeScript
2
star
75

example-of-generator-ngdoc

An example repository of generator-ngdoc(an Yeoman generator)
JavaScript
2
star
76

test-with-aot-summary

Explains how to Angular's AOT result in unit testing
TypeScript
2
star
77

copl-ts

CoPL本のTypeScript実装
TypeScript
2
star
78

astsx

TypeScript
2
star
79

prignore

Chrome-extension for GitHub PR
JavaScript
2
star
80

abacus-ts

Calculator implemented by only TypeScript type operation
TypeScript
1
star
81

puppeteer-coverage-study

TypeScript
1
star
82

pkg-study

JavaScript
1
star
83

sewordle

A chrome extension which generates tag cloud using user query keywords inputed at search-engine.
JavaScript
1
star
84

react-falcor-demo

Demonstration of Falcor and React
TypeScript
1
star
85

nopmdcheck

A jenkins plugin to check "NOPMD" comments in workspace.
JavaScript
1
star
86

type-apollo-local-state

TypeScript
1
star
87

fuse-postcss-example

A Fuse-Box with PostCSS example repository.
CSS
1
star
88

ts-api-study

TypeScript
1
star
89

dotson

TypeScript
1
star
90

prisma-dmmf-viewer

Display Prisma DMMF(Data Model Meta Format)
JavaScript
1
star
91

typescript-api-tutrial

1
star
92

first-liquidfun

JavaScript
1
star
93

apollo-client-37-study

TypeScript
1
star
94

ccvsample

JavaScript
1
star
95

ossc-hackathon-ardrone-14

JavaScript
1
star
96

Quramy

1
star
97

crudsample

this is a sample application on node (express + mongoose).
JavaScript
1
star
98

reproduce-apollo-react-memleak

To reproduce react-apollo memory leak
TypeScript
1
star
99

groovy-labo

Groovy
1
star
100

es7study

JavaScript
1
star