@toptal/davinci-graphql-codegen-extensions

1.0.4 • Public • Published

@toptal/davinci-graphql-codegen-extensions

A collection of extensions for the Graphql Code Generator.

The currently available extensions:

  • Schema loader - preprocessor for GQL schema that filters out enum values hidden from the consumers
  • Enums plugin - a plugin that generates a type for a mapping object between enum and the target type; by default all the enum values are required to be specified in the object, values that are marked with a special annotation become optional

Usage

Schema loader

The back-end can mark a new enum value as hidden with tt_earlySupportHidden directive.

enum StatusEnum {
  ACTIVE
  INACTIVE
  PENDING @tt_earlySupportHidden
}

Such annotated values will be removed from the schema used for types generation and won't be included in the Typescript enum:

enum StatusEnum {
  ACTIVE = 'ACTIVE',
  INACTIVE = 'INACTIVE'
}
Configuration

Configure your schema to use @toptal/davinci-graphql-codegen-extensions/schema-loader loader:

schema:
  - schema.graphql
      loader: @toptal/davinci-graphql-codegen-extensions/schema-loader
documents: ./src/**/*.graphql
generates:
  ./src/types.ts:
    plugins:
      - typescript
      - typescript-operations

Enums plugin

The back-end can mark a new enum value as optional with tt_earlySupport directive.

enum StatusEnum {
  ACTIVE
  INACTIVE
  PENDING @tt_earlySupport
}

As a result the generate file will contain a type GraphqlEnumMapping

export type GraphqlEnumMapping<EnumType extends keyof any, ValueType>

which by default maps to a regular record Record<EnumType, ValueType>, but marks all annotated enum values as optional. This type can be used in the objects and functions that deal with the enum value and know how to treat missing mappings.

const mapping: GraphqlEnumMapping<StatusEnum, string> = {
  [StatusEnum.ACTIVE]: 'Active',
  [StatusEnum.INACTIVE]: 'Inactive',
  // StatusEnum.PENDING is optional
}
Configuration

Add @toptal/davinci-graphql-codegen-extensions/enums-plugin plugin to your configuration:

schema: schema.graphql
documents: ./src/**/*.graphql
generates:
  ./src/types.ts:
    plugins:
      - typescript
      - @toptal/davinci-graphql-codegen-extensions/enums-plugin

Readme

Keywords

Package Sidebar

Install

npm i @toptal/davinci-graphql-codegen-extensions

Weekly Downloads

1,331

Version

1.0.4

License

SEE LICENSE IN LICENSE.MD

Unpacked Size

7.28 kB

Total Files

7

Last publish

Collaborators

  • talbot