Search code examples
typescriptenumsgraphqlapolloexpress-graphql

Share enum in Graphql


Just started learning GraphQL and I would like to share an enum that I exported in a express apollo server.

./src/shared/fruitsEnum.ts

export enum fruitsEnum{
    APPLE,
    ORANGE
}

Import the enum

./src/market/fruits.ts

import { fruitsEnum } from "./src/shared/fruitsEnum.ts"

export const typeDef = `
    type Fruit{
        id: ID
        fruitName: fruitsEnum
    }

    type Query{
    ...
    }
`

I tried doing this but I am getting Error: Unknown type fruitsEnum. The reason that I put the enum in a separate location is because the same enum might be used at other schema. My goal is to have a shareable enum type.


Solution

  • Typescript enum != graphQL enum

    Enum needs to be defined in graphQL 'context' as in docs, so it will work this way:

    export const typeDef = `
    
      enum fruitsEnum{
        APPLE,
        ORANGE
      }
    
      type Fruit{
        id: ID
        fruitName: fruitsEnum
      }
    
      type Query{
      ...
      }
    

    You can use type-graphql to 'connect' them (typescript and graphql contexts) and (share between client and server) without explicit [typescript defined] enum definition inside typDef.

    More info here