SubRight
SubRight

Reputation: 15

ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?)

I keep getting such errors:

[Nest] 21020  - 07.02.2024, 18:50:03   ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?). Please make sure that the argument UserControl at index [0] is available in the AuthModule context.

Potential solutions:
- Is AuthModule a valid NestJS module?
- If UserControl is a provider, is it part of the current AuthModule?
- If UserControl is exported from a separate @Module, is that module imported within AuthModule?
  @Module({
    imports: [ /* the Module containing UserControl */ ]
  })

But I just don't understand what else I should add to providers/imports/controllers. There is my DBModule:

@Module({
  imports: [],
  providers: [UserControl, PasswordManager, PrismaClient],
  controllers: [],
  exports: []
})

export class DBModule {}

AuthService:

@Injectable()
export class AuthService {
  constructor(private readonly userService: UserControl) {}
  public async register(body: UserData): Promise<any> {
    const requiredFields = ['login', 'plainPass', 'email'];
    const missingFields = [];
    // Check required fields exists
    for (const key in body) {
      if (
        requiredFields.includes(key) &&
        (body[key] === null || body[key] === undefined)
      ) {
        missingFields.push(body[key]);
      }
    }
    if (missingFields.length > 0) {
      throw new BadRequestException(
        `Missing ${missingFields.length} fields: ${missingFields}`,
      );
    }
    const newUser = await this.userService.registerUser(body);
    if (newUser) {
      return { success: true, user: newUser };
    }
  }
}

AuthModule

@Module({
  imports: [DBModule],
  controllers: [AuthController],
  providers: [AuthService],
})
export class AuthModule {}

UserControl

@Injectable()
export class UserControl {
  constructor(
    private readonly prisma: PrismaClient,
    private readonly passMngr: PasswordManager,
  ) {}
  private getById(id: number) {
    return this.prisma.users.findUniqueOrThrow({
      where: {
        user_id: id,
      },
    });
  }
  public async isValidLogin(login: string): Promise<boolean> {
    if (this.prisma.users.findFirst({ where: { login: login } }) === null) {
      return true;
    }
    return false;
  }

  public async isValidEmail(email: string): Promise<boolean> {
    if (
      (await this.prisma.users.findFirst({ where: { email: email } })) === null
    ) {
      return true;
    }
    return false;
  }
  public async registerUser(userData: UserData) {
    // Check are login and/or email already registered
    const emailValid = await this.isValidEmail(userData.email);
    const loginValid = await this.isValidLogin(userData.login);

    if (loginValid && emailValid) {
      // Hashing password by PasswordManager
      const passHash = await this.passMngr.hashPassword(userData.plainPass);
      const { login, email, firstName, lastName } = userData;
      // Creating new line in DB with registry data
      return await this.prisma.users.create({
        data: {
          login: login,
          password_hash: Buffer.from(passHash, 'utf-8'),
          email: email,
          first_name: firstName,
          last_name: lastName,
        },
        select: {
          user_id: true,
          login: true,
          first_name: true,
          is_email_verified: true,
          registry_date: true,
        },
      });
    } else {
      throw new BadRequestException(
        `${
          !emailValid && !loginValid
            ? 'Email and Login are'
            : !emailValid
              ? 'Email is '
              : loginValid
                ? ''
                : 'Login is '
        } already used.`,
      );
    }
  }
}

I already tried to export providers, but they are already in DBModule, so I think they all should be exported by default when I import DBModule. I asked ChatGPT, but all the advice he gave me was pretty useless like "your code looks correct try to check if the UserControl class is exported correctly" and the like, however it didn't bring any results.

Upvotes: 0

Views: 123

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70450

Add UserControl to the exports array of the DBModule metadata

Upvotes: 0

Related Questions