在 NestJS graphQL 模型中使用 prisma 的枚举

fra*_*tus 2 enums graphql nestjs prisma

我应该返回的对象:

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

  @Field(() => [Level])
  level: Level[]
}
Run Code Online (Sandbox Code Playgroud)

Level 是 prisma 生成的枚举,在 schema.prisma 中定义:

enum Level {
  EASY
  MEDIUM
  HARD
}
Run Code Online (Sandbox Code Playgroud)

现在我尝试在 GraphQL Mutation 中返回此 User 对象:

enum Level {
  EASY
  MEDIUM
  HARD
}
Run Code Online (Sandbox Code Playgroud)

运行此代码时,我收到以下错误:

UnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL output type for the "Level". Make sure your class is decorated with an appropriate decorator.
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?prisma 的枚举不能用作字段吗?

Éme*_*nto 6

当然可以。

import { Level } from '@prisma/client'

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

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

registerEnumType(Level, {
  name: 'Level',
});
Run Code Online (Sandbox Code Playgroud)

你应该使用registerEnumType+@Field(() => Enum)

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