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

NestJS中PrismaService注入后undefined问题求助

问题排查与解决方案

调用创建用户功能时出现TypeError: Cannot read properties of undefined (reading 'user'),提示PrismaUserRepository.create方法中的prisma为undefined。

核心原因

  1. PrismaUserRepository类未添加@Injectable()装饰器,NestJS的依赖注入系统无法识别该类,导致构造函数中的PrismaService实例未被注入,this.prisma变为undefined,进而调用this.prisma.user.create时触发错误。
  2. create方法存在逻辑错误:当用户创建成功(createdUser存在)时反而返回null,会导致业务逻辑异常。

解决方案

1. 为PrismaUserRepository添加依赖注入装饰器

在PrismaUserRepository类上添加@Injectable()装饰器,并导入对应的模块:

修改后的users-repository.ts代码:

import { Injectable } from '@nestjs/common'; // 新增导入
import { UserRepository } from "src/application/repositories/users-repository";
import { PrismaService } from "../prisma.service";
import { CreateUserDTO, FindUserDTO, UpdateUserDTO } from "src/core/dtos/user.dto";
import { User, UserWithoutPassword } from "src/core/entities/user.entity";

@Injectable() // 新增装饰器,让NestJS管理该类的依赖注入
export class PrismaUserRepository implements UserRepository {
    constructor(private prisma: PrismaService) { }

    async create(user: CreateUserDTO): Promise<User | null> {
        try {
            const createdUser = await this.prisma.user.create({ data: user });
            return createdUser; // 创建成功返回用户实例
        } catch (error) {
            // 可根据需要处理Prisma抛出的异常,比如邮箱重复等
            console.error('创建用户失败:', error);
            return null; // 创建失败返回null
        }
    }

    // 补充实现其他抽象方法,避免编译报错
    async findByEmail(email: string): Promise<User | null> {
        return this.prisma.user.findUnique({ where: { email } });
    }

    async findAll(query: FindUserDTO): Promise<UserWithoutPassword[]> {
        return this.prisma.user.findMany({ select: { id: true, email: true, name: true } });
    }

    async findOne(id: string): Promise<UserWithoutPassword | null> {
        return this.prisma.user.findUnique({ where: { id }, select: { id: true, email: true, name: true } });
    }

    async update(id: string, user: UpdateUserDTO): Promise<UserWithoutPassword | null> {
        return this.prisma.user.update({ where: { id }, data: user, select: { id: true, email: true, name: true } });
    }

    async remove(id: string): Promise<UserWithoutPassword | null> {
        return this.prisma.user.delete({ where: { id }, select: { id: true, email: true, name: true } });
    }
}

2. 修正create方法的逻辑错误

原代码中if (createdUser) { return null; }的逻辑完全颠倒,修改为创建成功返回用户实例,捕获异常后返回null,同时处理Prisma可能抛出的错误(如唯一约束冲突)。

3. 补充抽象方法的实现

由于PrismaUserRepository实现了UserRepository抽象类,必须实现所有抽象方法,否则会出现编译错误,上述代码已补充基础实现,可根据实际业务需求调整。

验证步骤

  1. 重启NestJS服务,确保依赖注入正常生效。
  2. 调用创建用户接口,检查是否成功创建用户并返回正确数据。
  3. 测试异常场景(如重复邮箱),确保错误处理逻辑正常工作。

内容的提问来源于stack exchange,提问作者Victor Matheus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:25:25