You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS集成Prisma Enum构建报错问题求助

NestJS + Prisma 构建时枚举报错:Cannot convert undefined or null to object

问题根因

报错本质是编译阶段静态计算的装饰器参数导致的加载时序问题:

  • 调试模式下,NestJS热重载会在运行时动态初始化Prisma Client,枚举RoomSharingType已完成加载,Object.values()能正常执行
  • 生产构建时,TypeScript会静态计算装饰器的message参数,此时Prisma Client的枚举还未被正确导入初始化,RoomSharingType为undefined,触发Object.values()的类型错误

解决方案

方案1:用工厂函数延迟计算错误消息(推荐)

利用class-validator的message支持函数类型的特性,将枚举值的计算延迟到运行时执行:

import { RoomSharingType } from '@prisma/client';
import { IsEnum, IsString } from 'class-validator';

export class ValidationDemo {
  @IsEnum(RoomSharingType, {
    // 改为函数,运行时才会获取枚举值
    message: () => 
      'OTP Type must be one of these values: ' + Object.values(RoomSharingType).join(', ')
  })
  @IsString()
  type: RoomSharingType;
}

方案2:手动同步枚举定义

在代码中手动定义与Prisma Schema一致的枚举,避免依赖Prisma Client的动态加载:

  1. 创建独立枚举文件(如src/enums/room-sharing-type.enum.ts):
export enum RoomSharingType {
  TYPE1 = 'TYPE1',
  TYPE2 = 'TYPE2'
}
  1. 确保Prisma Schema的枚举与手动定义完全一致:
enum RoomSharingType {
  TYPE1
  TYPE2
}
  1. DTO中导入手动定义的枚举:
import { RoomSharingType } from '../enums/room-sharing-type.enum';
import { IsEnum, IsString } from 'class-validator';

export class ValidationDemo {
  @IsEnum(RoomSharingType, {
    message: 'OTP Type must be one of these values: ' + Object.values(RoomSharingType).join(', ')
  })
  @IsString()
  type: RoomSharingType;
}

方案3:确保Prisma Client生成路径正确

检查schema.prisma的生成器配置,确保Client输出路径在构建时能被正确解析:

generator client {
  provider = "prisma-client-js"
  output = "./node_modules/@prisma/client" // 默认路径,避免自定义路径导致的解析问题
}

执行npx prisma generate重新生成Client后再构建。

验证方式

执行nest build后启动生产环境服务,检查是否再触发该错误,同时验证DTO的枚举校验功能正常。

内容的提问来源于stack exchange,提问作者Aayush Bhattarai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:04:54