3

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'
}

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

2 Comments

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 stackoverflow.com/questions/66929685/…
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.