Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

graphql-typescript-definitions

Package Overview
Dependencies
Maintainers
2
Versions
120
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-typescript-definitions

Generate TypeScript definition files from .graphql documents

  • 0.10.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
39K
increased by5.21%
Maintainers
2
Weekly downloads
 
Created
Source

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;
    

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 this file to reference these types in other application code as well; in particular, GraphQL enums are turned into corresponding TypeScript enums. This file 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

yarn run graphql-typescript-definitions 'src/**/*.graphql' --schema-path 'build/schema.json' --schema-types-path 'src/schema.ts'

Optionally, you can pass the --watch flag in order to regenerate the TypeScript definition files on changes to the GraphQL files. You can also pass the --add-typename flag in order to always generate a __typename field for object types, and an --enum-format type which specifies the casing to use for enum types generated from the schema.

Node

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

const builder = new Builder({
  graphQLFiles: 'src/**/*.graphql',
  schemaPath: 'build/schema.json',
  schemaTypesPath: 'src/schema.ts',
});

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

FAQs

Package last updated on 27 Jul 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc