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

how-to-convert-a-typescript-built-in-enum-to-a-graphql-enum

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,
);

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
}

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),
  });

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

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
the-comprehensive-guide-to-cloud-penetration-testing:-ensuring-data-security

The Comprehensive Guide to Cloud Penetration Testing: Ensuring Data Security

Next Post
ids-appoints-dr.-michael-berger-to-management-board

IDS Appoints Dr. Michael Berger to Management Board

Related Posts