NodeJS NestJS类验证器,带有Prisma枚举的IsEnum

r1zhe5dt  于 2022-12-03  发布在  Node.js
关注(0)|答案(1)|浏览(173)

我有一个正在制作的restful应用程序。我的prisma模式中的模型如下所示:

model Customers {
  id                    Int             @id @default(autoincrement()) @map("id")
  customerType          Customer_types  @relation(fields: [customer_type_id], references: [id])
  customer_type_id      Int             @map("customer_type_id")
  identification_number String          @unique @map("identification_number")
  customer_names        String          @map("customer_names")
  msisdn                String          @unique @map("msisdn")
  email                 String?         @unique @map("email")
  gender                CustomerGender @map("gender")
  customer_source       CustomerSource         @map("customer_source")
  created_at            DateTime        @default(now()) @map("created_at")
  updated_at            DateTime        @updatedAt @map("updated_at")

  payments           Transactions[]
  services           Services[]
  customer_referrals Customer_referrals[] @relation("customer_id")
  referrals          Customer_referrals[] @relation("referree_id")
  addressess         Addresses[]

  @@map("qp_customers")
}

enum CustomerGender {
  Male
  Female
}

enum CustomerSource {
  Website
  Facebook
  Twitter
  Instagram
  TV
  Radio
  Walkin
  FieldVisit
}

我需要对某些字段进行限制,因此我对性别和客户源使用枚举。在Restful API上,我使用带有类验证器的dto。为此,我对性别和客户源使用IsEnum类验证器。

export class AuthDto {
  @IsEmail()
  @IsOptional()
  email: string;

  @IsString()
  @IsOptional()
  password: string;

  @IsInt()
  @IsNotEmpty()
  customer_type_id: number;

  @IsString()
  @IsNotEmpty()
  msisdn: string;

  @IsString()
  @IsNotEmpty()
  identification_number: string;

  @IsString()
  @IsNotEmpty()
  customer_names: string;

  @IsInt()
  @IsNotEmpty()
  referree_id: number;

  @IsInt()
  @IsNotEmpty()
  user_id: number;

  @IsEnum(CustomerGender)
  @IsNotEmpty()
  gender: string;

  @IsEnum(CustomerSource)
  @IsNotEmpty()
  customer_source: string;
}

但是,我收到此错误:

src/auth/auth.service.ts:38:11 - error TS2322: Type 'string' is not assignable to type 'CustomerGender'.

38           gender: dto.gender,
             ~~~~~~

  node_modules/.prisma/client/index.d.ts:16658:5
    16658     gender?: CustomerGender | null
              ~~~~~~
    The expected type comes from property 'gender' which is declared here on type '(Without<CustomersCreateInput, CustomersUncheckedCreateInput> & CustomersUncheckedCreateInput) | (Without<...> & CustomersCreateInput)'

应用程序是RESTFUL API。这里可能有什么问题。即使我把IsEnum改为IsString,错误仍然存在。我可能做错了什么?

watbbzwu

watbbzwu1#

你可能已经解决了这个问题,但我会张贴这个答案,以防其他人面临同样的问题。
问题就在这里

@IsEnum(CustomerSource)
  @IsNotEmpty()
  customer_source: string;

您已将CustomerSource类型分配给枚举验证器,但在其下面,您已将属性设置为字符串类型,这是两种不同的类型,因此出现错误:

error TS2322: Type 'string' is not assignable to type 'CustomerGender'.

这应该是可行:

@IsEnum(CustomerSource)
  @IsNotEmpty()
  customer_source: CustomerSource;

相关问题