mongodb 错误:Nest无法解析UserRepository(?)

plupiseo  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(139)

第一个月
我尝试在登录用例中访问userRepository。我尝试了几种方法,错误一直在变化,直到我遇到了这个我无法克服的错误。在其他模块中访问userRepository的最佳方式是什么?
login.usecase.ts

import { JwtService } from '@nestjs/jwt';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { IBcryptService } from '../../domain/shared/adapters/bcrypt.interface';
import { AuthLoginDto } from '../../infrastructure/controllers/auth/auth.dto';
import UserRepository from '../../infrastructure/repository/mongoose/user/user.repository';

@Injectable()
export default class LoginUseCase {
  constructor(
    @Inject('UserRepository')
    private userRepository: UserRepository,
    @Inject('JwtService')
    private jwtService: JwtService,
    @Inject('BcryptService')
    private bcryptService: IBcryptService,
  ) {}

  async execute({ email, password }: AuthLoginDto): Promise<{
    accessToken: string;
  }> {
    const user = await this.userRepository.findOneByEmail(email);

    if (!user) {
      throw new Error('User not found');
    }

    const isMatch = await this.bcryptService.compare(password, user.password);

    if (!isMatch) {
      throw new UnauthorizedException('Password not match');
    }

    const payload = {
      id: user.id,
      email: user.email,
    };

    return {
      accessToken: await this.jwtService.signAsync(payload),
    };
  }
}

字符串
auth.module.ts

import { Module, forwardRef } from '@nestjs/common';
import { AuthController } from '../../controllers/auth/auth.controller';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import LoginUseCase from '../../../usecase/auth/login.usecase';
import { JwtStrategy } from '../../common/strategies/jwt-strategy';
import UserRepository from '../../repository/mongoose/user/user.repository';
import { UserModule } from '../user/user.module';
import { BcryptService } from '../../services/bcrypt/bcrypt.service';
import { BcryptModule } from '../bcrypt/bcrypt.module';

@Module({
  imports: [
    JwtModule.register({
      global: true,
      secret: process.env.JWT_SECRET,
      signOptions: { expiresIn: '1h' },
    }),
    PassportModule,
    UserModule,
    BcryptModule,
  ],
  controllers: [AuthController],
  providers: [
    LoginUseCase,
    JwtStrategy,
    {
      provide: 'UserRepository',
      useClass: UserRepository,
    },
    {
      provide: 'JwtService',
      useClass: JwtService,
    },
    {
      provide: 'BcryptService',
      useClass: BcryptService,
    },
  ],
  exports: [LoginUseCase],
})
export class AuthModule {}


user.module.ts

import { Module } from '@nestjs/common';
import { UserController } from '../../controllers/user/user.controller';
import { MongooseModule } from '@nestjs/mongoose';
import UserRepository from '../../repository/mongoose/user/user.repository';
import { User, UserSchema } from '../../repository/mongoose/user/user.model';

@Module({
  imports: [
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
  ],
  controllers: [UserController],
  providers: [UserRepository],
  exports: [UserRepository],
})
export class UserModule {}


如果我尝试通过Controller访问userRepository,它可以正常工作,但我无法通过usecase登录访问它
user.repository.ts

import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { UserDocument, User as UserModel } from './user.model';
import UserRepositoryInterface from '../../../../domain/user/repository/user.repository.interface';
import User from '../../../../domain/user/entity/user';

@Injectable()
export default class UserRepository implements UserRepositoryInterface {
  constructor(
    @InjectModel(UserModel.name) private userModel: Model<UserDocument>,
  ) {}

  async create(entity: User): Promise<void> {
    const createdUser = new this.userModel({
      id: entity.id,
      email: entity.email,
      password: entity.password,
    });
    createdUser.save();
  }

  async update(id: string, entity: User): Promise<void> {
    await this.userModel.updateOne(
      { id: id },
      {
        id: entity.id,
        email: entity.email,
        password: entity.password,
      },
    );
  }

  async find(id: string): Promise<User> {
    const user = await this.userModel.findOne({ id: id });
    return new User(user.id, user.email, user.password);
  }

  async findOneByEmail(email: string): Promise<User> {
    const user = await this.userModel.findOne({ email: email });
    return new User(user.id, user.email, user.password);
  }

  async findAll(): Promise<User[]> {
    const users = await this.userModel.find();
    return users.map((user) => {
      return new User(user.id, user.email, user.password);
    });
  }
}


app.module.ts

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from './infrastructure/modules/auth/auth.module';
import { UserModule } from './infrastructure/modules/user/user.module';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { BcryptModule } from './infrastructure/modules/bcrypt/bcrypt.module';

@Module({
  imports: [
    UserModule,
    AuthModule,
    BcryptModule,
    PassportModule,
    JwtModule.register({
      secret: process.env.secret,
    }),
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    MongooseModule.forRoot('mongodb://localhost/teste'),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

x8diyxa7

x8diyxa71#

AuthModule中将useClass: UserRepository更改为useExisting: UserRepository,它应该可以正常工作。这里的问题是Nest试图使用AuthModule上下文中可用的提供程序创建UserRepository的新示例,而不是从UserModule上下文中重用UserReposiotyr。通过使用useExisting而不是useClass,您可以重用已在当前上下文中创建的提供程序(您的UserRepository是因为UserMoudleexports),而不是完全创建新示例

相关问题