2

I use graphql-codegen to generate type files.

As an example, let's say I have the following in my schema.graphql file:

enum cities {
 JOHANNESBURG
 CAIRO
 NEW_YORK
 LONDON
 BEIJING
}

The output in my generated-types.ts file is as follows:

export enum cities {
 Johannesburg = 'JOHANNESBURG'
 Cairo = 'CAIRO'
 NewYork = 'NEW_YORK'
 London = 'LONDON'
 Beijing = 'BEIJING'
}

Is there a way for me to 'override' the value of the enum before codegen runs? Perhaps something as follows (which I obviously tried):

enum cities {
 JOHANNESBURG: 'JNB'
 CAIRO: 'CAI'
 NEW_YORK: 'NYC'
 LONDON: 'LON'
 BEIJING: 'BEI'
}

which in turn should produce:

export enum cities {
 Johannesburg = 'JNB'
 Cairo = 'CAI'
 NewYork = 'NYC'
 London = 'LON'
 Beijing = 'BEI'
}
techedemic
  • 341
  • 2
  • 6

1 Answers1

7

not sure if I'm too late, but you probably can use the enumValues to customize your internal enum values. Here is the documentation. For example:

./types.ts

export enum cities {
 Johannesburg = 'JNB'
 Cairo = 'CAI'
 NewYork = 'NYC'
 London = 'LON'
 Beijing = 'BEI'
}

./codegen.yml

generates:
  src/graphql.types.ts:
    config:
      useIndexSignature: true
      enumValues:
        cities: ./types#cities // path to your custom types
    plugins:
      - typescript
      - typescript-resolvers
Ewe Tek Min
  • 855
  • 10
  • 19
  • Thank you! This answer was exactly what I needed after migrating my graphql endpoint from headless wordpress to onegraph. The former uses actual string names for enum values whereas the latter uses numeric enums. Apollo was not loving numeric enums, even started a thread on here about it https://stackoverflow.com/questions/66929685/onegraph-and-graphql-codegen-outputs-enums-with-numeric-values – Andrew Ross Apr 03 '21 at 10:13
  • 5
    Why can't codegen derive the values from the specified values set in GraphQL? Manually creating and mapping values defeats the purpose of autogenerating those same values you need. – bombillazo Jul 06 '22 at 18:37