How to convert a TypeScript built-in enum to a GraphQL enum

Samuel Durante - Feb 5 - - Dev Community

At Woovi we are GraphQL lovers, hence we develop many helpers around this tool to bring a good developer experience.

A helper that we developed is graphqlEnumBuilder, this helper allows us to convert a TypeScript built-in enum into a GraphQLEnum without difficulty. Thus, if you add a new value in your TypeScript enum, you don't need to edit your GraphQL enum, because it's generated from your TypeScript enum.

How it works

enum Gender {
  Male = 'Male',
  Female = 'Female',
}

const GenderEnumType = graphqlEnumBuilder(
  'GenderType',
  Gender,
);
Enter fullscreen mode Exit fullscreen mode

When you call this GenderEnumType in some query or mutation as an argument and generate your schema file, note that the GenderEnumType is declared as an enum in the GraphQL notation.

Here is an example:

enum GenderType {
  Male
  Female
}
Enter fullscreen mode Exit fullscreen mode

Code solution

import { GraphQLEnumType } from 'graphql';

type EnumObject = {
  [index: string]: string;
};

type EnumObjectResult = {
  [index: string]: {
    value: string;
  };
};
export const enumBuilderValues = <T = EnumObject>(
  constants: T,
): EnumObjectResult =>
  Object.keys(constants).reduce(
    (prev, curr) => ({
      ...prev,
      [curr]: {
        value: constants[curr],
      },
    }),
    {},
  );

export const graphqlEnumBuilder = <T = EnumObject>(name: string, values: T) =>
  new GraphQLEnumType({
    name,
    values: enumBuilderValues(values),
  });
Enter fullscreen mode Exit fullscreen mode

Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

If you want to work with us, we are hiring!


Photo by Tom Hermans on Unsplash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .