graphql-typescript-definitions
Generate TypeScript definition files from .graphql documents
Last updated a month ago by shopify-dep .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install graphql-typescript-definitions 
SYNC missed versions from official npm registry.

graphql-typescript-definitions

Generate TypeScript definition files from .graphql documents

Installation

npm install graphql-typescript-definitions --save-dev

or, with Yarn:

yarn add graphql-typescript-definitions --dev

Usage

This package will generate matching .d.ts files for each .graphql file you specify. It will generate types in the following format:

  • A default export for the type that will be generated by a GraphQL loader (GraphQL’s DocumentNode type, but augmented as graphql-typed’s DocumentNode which includes additional type details about the operation).

  • An interface for each query, mutation, and fragment, named <OpertionName><Query | Mutation | Fragment>Data. For example, query Home {} becomes export interface HomeQueryData {}.

  • A namespace for each operation that includes any nested types. Nested types are named in pascal case using their keypath from the root of the operation. For example, if we imagine the following GraphQL schema (using the GraphQL IDL):

    type Person {
      name: String!
      relatives: [Person!]!
    }
    
    type Query {
      person: Person
    }
    

    and the following query:

    query Someone {
      person {
        name
        relatives {
          name
        }
      }
    }
    

    The following exports would be generated:

    export interface SomeoneQueryData {
      person?: SomeoneQueryData.Person | null;
    }
    
    export namespace SomeoneQueryData {
      export interface Person {
        name: string;
        relatives: SomeoneQueryData.PersonRelatives[];
      }
    
      export interface PersonRelatives {
        name: string;
      }
    }
    

    This allows you to use the full query’s type, as well as any of the subtypes that make up that query type. This is particularly useful for list or nullable types, where you can directly the access the underlying type without any additional help from TypeScript:

    import someoneQueryDocument, {SomeoneQueryData} from './Someone.graphql';
    
    let data: SomeoneQueryData;
    let person: SomeoneQueryData.Person;
    

Operation

On startup this tool performs the following actions:

  • Loads all schemas
  • Extracts all enums, input objects, and custom scalars as schema types
  • Writes the schema types to types.ts (or ${projectName}-types.ts for named projects)
    • Written in directory provided by --schema-types-path argument
    • Override --schema-types-path per project with the schemaTypesPath extension

Configuration

This tool reads schema information from a .graphqlconfig file in the project root.

Examples

A project configuration with a schemaTypesPath override

{
  "schemaPath": "build/schema.json",
  "includes": "app/**/*.graphql",
  "extensions": {
    "schemaTypesPath": "app/bar/types/graphql"
  }
}

Type Generation

Nullability

As demonstrated in the root person field in the example above, nullable fields are represented as optional types, in a union with null. Nullable items in list fields (i.e., [Person]!) are represented as a union type with null.

Interfaces and Unions

Interface an union fields are represented as union types in cases where there are spreads that could result in different fields on different concrete types. The type names for these cases are named the same as the default naming (pascal case version of the keypath for the field), but with the type condition appended to the end. All cases not covered by fragments are extracted into a type with a postpended Other name.

# Schema
interface Named {
  name: String!
}

type Person implements Named {
  name: String!
  occupation: String
}

type Dog implements Named {
  name: String!
  legs: Int!
}

type Cat implements Named {
  name: String!
  livesLeft: Int!
}

type Horse implements Named {
  name: String!
  topSpeed: Float!
}

type Query {
  named: Named
}
# Query
query SomeNamed {
  named {
    name
    ... on Person {
      occupation
    }
    ... on Dog {
      legs
    }
  }
}
// generated types
export interface SomeNamedData {
  named?:
    | SomeNamedData.NamedPerson
    | SomeNamedData.NamedDog
    | SomeNamedData.NamedOther
    | null;
}

export namespace SomeNamedData {
  export interface NamedPerson {
    __typename: 'Person';
    name: string;
    occupation?: string | null;
  }
  export interface NamedDog {
    __typename: 'Dog';
    name: string;
    legs: number;
  }
  export interface NamedOther {
    __typename: 'Cat' | 'Horse';
    name: string;
  }
}

Note that the above example assumes that you specify the --add-typename argument. These types are only useful when a typename is included either explicitly or with this argument, as otherwise there is no simple way for TypeScript to disambiguate the union type.

Schema Types

Input types (enums, input objects, and custom scalars) are generated once, in a central location, and imported within each typing file. You can use these definitions to reference the schema types in other application code as well; in particular, GraphQL enums are turned into corresponding TypeScript enums. The schema types directory is specified using the --schema-types-path argument (detailed below), and the format for the generated enums can be specified using the --enum-format option.

CLI

graphql-typescript-definitions --schema-types-path app/types

As noted above, the configuration of your schema and GraphQL documents is done via a .graphqlconfig file, as this allows configuration to shared between tools. The CLI does support a few additional options, though:

  • --schema-types-path: specifies a directory to write schema types (REQUIRED)
  • --watch: watches the include globbing patterns for changes and re-processes files (default = false)
  • --cwd: run tool for .graphqlconfig located in this directory (default = process.cwd())
  • --add-typename: adds a __typename field to every object type (default = true)
  • --enum-format: specifies output format for enum types (default = undefined)
    • Options: camel-case, pascal-case, snake-case, screaming-snake-case
    • undefined results in using the unchanged name from the schema (verbatim)
  • --custom-scalars: specifies custom types to use in place of scalar types in your GraphQL schema. See below for details.

Examples

# run tool for .graphqlconfig in current directory, produces ./app/graphql/types
graphql-typescript-definitions --schema-types-path app/graphql/types

# run watcher for .graphqlconfig in current directory, produces ./app/graphql/types
graphql-typescript-definitions --schema-types-path app/graphql/types --watch

# run tool for .graphqlconfig in a child directory, produces ./src/app/graphql/types
graphql-typescript-definitions --cwd src --schema-types-path app/graphql/types

--custom-scalars

By default, all custom scalars are exported as an alias for string. You can export a different type for these scalars by passing in a --custom-scalars option. This option is a JSON-serialized object that specifies what custom type to import from a package and re-export as the type for that scalar. For example, assuming the following schema:

scalar HtmlString

You may want a custom TypeScript type for any field of this GraphQL type (for example, to restrict functions to use only this type, and not any arbitrary string). Assuming you have an installed npm package by the name of my-custom-type-package, and this package exports a named SafeString type, you could pass the following --custom-scalars option:

yarn run graphql-typescript-definitions --schema-path 'build/schema.json' --schema-types-path 'src/schema' --custom-scalars '{"HtmlString": {"name": "SafeString", package: "my-custom-type-package"}}'

With this configuration, your custom scalar would be exported roughly as follows:

import {SafeString} from 'my-custom-type-package';
export type HtmlString = SafeString;

Node

const {Builder} = require('graphql-typescript-definitions');

const builder = new Builder({
  schemaTypesPath: 'app/graphql/types',
});

builder.on('build', (build) => {
  // See the source file for details on the shape of the object returned here
  console.log(build);
});

builder.on('error', (error) => {
  console.error(error);
});

// Optionally, you can pass {watch: true} here to re-run on changes
builder.run();

As with the CLI, you can pass options to customize the build and behavior:

  • watch
  • enumFormat (use the exported EnumFormat enum)
  • graphQLFiles
  • schemaPath
  • schemaTypesPath
  • customScalars
  • config (custom GraphQLConfig instance)

Current Tags

  • 0.18.1                                ...           latest (a month ago)
  • 0.16.0-beta.1                                ...           next (9 months ago)

43 Versions

  • 0.18.1                                ...           a month ago
  • 0.18.0                                ...           2 months ago
  • 0.17.3                                ...           3 months ago
  • 0.17.2                                ...           8 months ago
  • 0.17.1                                ...           8 months ago
  • 0.17.0                                ...           8 months ago
  • 0.16.1                                ...           9 months ago
  • 0.16.0                                ...           9 months ago
  • 0.16.0-beta.1                                ...           9 months ago
  • 0.15.1                                ...           9 months ago
  • 0.15.0                                ...           a year ago
  • 0.14.0                                ...           a year ago
  • 0.13.3                                ...           a year ago
  • 0.13.2                                ...           a year ago
  • 0.13.1                                ...           a year ago
  • 0.13.0                                ...           a year ago
  • 0.12.1                                ...           a year ago
  • 0.12.0-beta.3                                ...           a year ago
  • 0.12.0-beta.2                                ...           a year ago
  • 0.12.0-beta.1                                ...           a year ago
  • 0.11.0                                ...           a year ago
  • 0.10.0                                ...           a year ago
  • 0.9.2                                ...           a year ago
  • 0.9.1                                ...           a year ago
  • 0.9.0                                ...           2 years ago
  • 0.8.2                                ...           2 years ago
  • 0.8.1                                ...           2 years ago
  • 0.7.5                                ...           2 years ago
  • 0.7.4                                ...           2 years ago
  • 0.7.3                                ...           2 years ago
  • 0.7.2                                ...           2 years ago
  • 0.7.1                                ...           2 years ago
  • 0.7.0                                ...           2 years ago
  • 0.6.3                                ...           3 years ago
  • 0.6.2                                ...           3 years ago
  • 0.6.1                                ...           3 years ago
  • 0.6.0                                ...           3 years ago
  • 0.5.2                                ...           3 years ago
  • 0.5.1                                ...           3 years ago
  • 0.5.0                                ...           3 years ago
  • 0.4.0                                ...           3 years ago
  • 0.3.0                                ...           3 years ago
  • 0.2.0                                ...           3 years ago
Downloads
Today 0
This Week 0
This Month 3
Last Day 0
Last Week 3
Last Month 63
Dependencies (16)
Dev Dependencies (4)

Copyright 2014 - 2016 © taobao.org |