Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enums from prisma in nestJS graphQL models

My object that is supposed to be returned:

@ObjectType()
export class User {
  @Field(() => String)
  email: string

  @Field(() => [Level])
  level: Level[]
}

Level is an enum generated by prisma, defined in schema.prisma:

enum Level {
  EASY
  MEDIUM
  HARD
}

Now I'm trying to return this User object in my GraphQL Mutation:

@Mutation(() => User, { name: 'some-endpoint' })

When running this code, I'm getting the following error:

UnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL output type for the "Level". Make sure your class is decorated with an appropriate decorator.

What am I doing wrong here? Can't enums from prisma be used as a field?

like image 780
fraktus Avatar asked Sep 17 '25 17:09

fraktus


2 Answers

Of course, you can.

import { Level } from '@prisma/client'

@ObjectType()
export class User {
  @Field(() => String)
  email: string

  @Field(() => Level)
  level: Level
}

registerEnumType(Level, {
  name: 'Level',
});

You should use registerEnumType + @Field(() => Enum)

https://docs.nestjs.com/graphql/unions-and-enums#enums

like image 77
Émerson Felinto Avatar answered Sep 19 '25 08:09

Émerson Felinto


You're probably missing the registration of the enum type in GraphQL:

// user.model.ts
registerEnumType(Level, { name: "Level" });
like image 34
Joulukuusi Avatar answered Sep 19 '25 08:09

Joulukuusi