Enums can be defined a number of different ways:
Using typescript enums
export enum Diet {
HERBIVOROUS,
CARNIVOROUS,
OMNIVORIOUS,
}
builder.enumType(Diet, {
name: 'Diet',
});
Using an array of strings
export const LengthUnit = builder.enumType('LengthUnit', {
values: ['Feet', 'Meters'] as const,
});
Note that we use as const
to allow ts to properly type our enum values.
Using a values object:
export const GiraffeSpecies = builder.enumType('GiraffeSpecies', {
values: {
Southern: {
description: 'Also known as two-horned giraffe',
value: 'giraffa',
},
Masai: {
value: 'tippelskirchi',
},
Reticulated: {
value: 'reticulata',
},
Northern: {
value: 'camelopardalis',
},
} as const,
});
Again we use as const
here to allow the enum values to be correctly inferred. The as const
can also be added to the values instead, or omitted if the values
are already defined using a
variable that typescript can type correctly.
Using a values object like this enables defining additional options like a description for each enum value.
Enums can be referenced either by the Ref
that was returned by calling builder.enumType
or by
using the typescript enum. They can be used either as arguments, or as field return types:
builder.objectFields('Giraffe', (t) => ({
height: t.float({
args: {
unit: t.arg({
type: LengthUnit,
required: true,
defaultValue: 'Meters',
}),
},
resolve: (parent, args) =>
args.unit === 'Meters' ? parent.heightInMeters : parent.heightInMeters * 3.281,
}),
diet: t.field({
description:
'While Giraffes are herbivores, they do eat the bones of dead animals to get extra calcium',
type: Diet,
resolve: () => Diet.HERBIVOROUS,
}),
species: t.field({
type: GiraffeSpecies,
resolve: () => 'camelopardalis' as const,
}),
}));