typescriptnestjsclean-architecture

NestJS provider undefined I can't find the reason


Prisma.service.ts

import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common'
import { PrismaClient } from '@prisma/client'

@Injectable()
export class PrismaService
  extends PrismaClient
  implements OnModuleInit, OnModuleDestroy
{
  constructor() {
    super({
      log: ['warn', 'error'],
    })
  }

  onModuleInit() {
    return this.$connect()
  }

  onModuleDestroy() {
    return this.$disconnect()
  }
}

users-repository.ts

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";



export class PrismaUserRepository implements UserRepository {
    constructor(private prisma: PrismaService) { }

    async create(user: CreateUserDTO): Promise<User> {
        
        const createdUser = await this.prisma.user.create({ data: user })

        if (createdUser) {
            return null;
        }


        return createdUser;
    }
}

abstract-user-repository.ts


import { User, UserWithoutPassword } from 'src/core/entities/user.entity';
import {CreateUserDTO, FindUserDTO, UpdateUserDTO} from '../../core/dtos/user.dto'

export abstract class UserRepository {
    abstract create(user: CreateUserDTO): Promise<User | null>

    abstract findByEmail(email: string): Promise<User | null>

    abstract findAll(query: FindUserDTO): Promise<UserWithoutPassword[]>

    abstract findOne(id: string): Promise<UserWithoutPassword | null>

    abstract update(id: string, user: UpdateUserDTO): Promise<UserWithoutPassword | null>

    abstract remove(id: string): Promise<UserWithoutPassword | null>
}

database.module.ts


import { Module } from "@nestjs/common";
import { PrismaService } from "./prisma/prisma.service";
import { UserRepository } from "../../application/repositories/users-repository";
import { PrismaUserRepository } from "./prisma/repositories/users-repository";


@Module({
    providers: [
        PrismaService,
        {
            provide: UserRepository,
            useClass: PrismaUserRepository,
        },
    ],
    exports: [
        UserRepository
    ],
})
export class DatabaseModule { }

When trying to create a user it says that prisma is undefined TypeError: Cannot read properties of undefined (reading 'user') at PrismaUserRepository.create (\src\infra\database\prisma\repositories\users-repository.ts:13:47)

I tried to check the imports and see if I had forgotten any nestJS decorators, but I didn't find any errors. I also ensured that Prisma is being connected when starting npm


Solution

  • I guess that's because you've missed the a @Injectable() on PrismaUserRepository, and that class has declared a dependency that Nestjs DI container should resolve