0

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.

calvert
  • 631
  • 10
  • 33

1 Answers1

3

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

xadm
  • 8,219
  • 3
  • 14
  • 25
  • Thanks. Let say if i don't use `type-graphql`, I have another file called `restaurant.ts` that will be using the same enum. I will be pasting the enum in the restaurant's schema from `fruits.ts` and of course without using the above package I will need to define the enum in the `fruits.ts's` schema. If I go this route, I will have 2 same enum defined at 2 different schemas – calvert Apr 17 '20 at 00:51
  • 1
    this is not a schema definition - ts enum has to be defined in the same shape in graphql, it's not imported/passed/compiled in ... see update – xadm Apr 17 '20 at 01:08
  • `it's not imported/passed/compiled in `, got it. Thank you again. – calvert Apr 17 '20 at 03:39