【问题标题】:how to resolve problem whem import repository in nestjs如何解决在nestjs中导入存储库的问题
【发布时间】:2021-07-13 15:09:31
【问题描述】:

我是 nestjs 的新手,当我尝试导出自定义存储库时遇到一个问题,我不知道如何解决它。

gas-station.repository.ts 我创建自定义存储库:

@Injectable()
class GasStationRepository implements IGasStationRepository {
  constructor(
    @InjectRepository(GasStation)
    private readonly gasStationRepository: Repository<GasStation>,
  ) {}

  //...
  public async createGasStation(
    gasStationDto: ICreateGasStationDto,
  ): Promise<GasStation> {
    const gasStation = this.gasStationRepository.create(gasStationDto);
    await this.gasStationRepository.save(gasStation);
    return gasStation;
  }

  public async bulkCreateGasStation(
    gasStations: ICreateGasStationDto[],
  ): Promise<GasStation[]> {
    return Promise.all(gasStations.map(this.createGasStation));
  }
}

export default GasStationRepository;

gas-station.module.ts 我认为导出我的存储库是正常的公式:


@Module({
  imports: [TypeOrmModule.forFeature([GasStation])],
  controllers: [GasStationController],
  providers: [
    GasStationService,
    {
      useClass: GasStationRepository,
      provide: GAS_STATION_REPOSITORY,
    },
  ],
  exports: [
    {
      useClass: GasStationRepository,
      provide: GAS_STATION_REPOSITORY,
    },
  ],
})
export class GasStationModule {}

user.module.ts 我导入 gasStationModule 以供使用存储库

@Module({
  imports: [TypeOrmModule.forFeature([User]), GasStationModule],
  controllers: [UserController],
  providers: [
    UserService,
    {
      useClass: UserRepository,
      provide: USER_REPOSITORY,
    },
  ],
})
export class UserModule {}

user.service.ts 我将使用存储库:

@Injectable()
export class UserService {
  constructor(
    @Inject(USER_REPOSITORY) private readonly userRepository: IUserRepository,
    @Inject(GAS_STATION_REPOSITORY)
    private readonly gasStationRepository: IGasStationRepository,
  ) {}
  async create(createUserDto: CreateUserDto) {
    const {
      type,
      branches,
      gasStations,
      email,
      password,
      ...props
    } = createUserDto;
    const existedUser = await this.userRepository.findByEmail(email);
    if (existedUser) {
      throw new BadRequestException('Usuário já cadastrado');
    }

    let gasStationList: ICreateGasStationDto[] = [];
    let branchList: ICreateBranchDto[] = [];

    if (type === 1 && gasStations && gasStations.length > 0) {
      gasStationList = await this.gasStationRepository.bulkCreateGasStation(
        gasStations,
      );
    } else if (type === 2 && branches && branches.length > 0) {
      branchList = [];
    }

    const hashedPassword = await hash(password, 8);

    const user = await this.userRepository.createUser({
      type,
      email,
      password: hashedPassword,
      ...(branchList.length > 0 && { branches: branchList }),
      ...(gasStationList.length > 0 && { gasStations: gasStationList }),
      ...props,
      active: false,
    } as ICreateUserDto);

    delete user.password;

    return user;
  }
//...
}

错误:

TypeError: Cannot read property 'gasStationRepository' of undefined
    at createGasStation (/media/michelkuguio/Novo volume/easypetro/nest/epetro/dist/modules/gas-station/gas-station.repository.js:30:33)
    at Array.map (<anonymous>)
    at GasStationRepository.bulkCreateGasStation (/media/michelkuguio/Novo volume/easypetro/nest/epetro/dist/modules/gas-station/gas-station.repository.js:35:40)
    at UserService.create (/media/michelkuguio/Novo volume/easypetro/nest/epetro/dist/modules/user/user.service.js:45:62)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async /media/michelkuguio/Novo volume/easypetro/nest/epetro/node_modules/@nestjs/core/router/router-execution-context.js:46:28
    at async /media/michelkuguio/Novo volume/easypetro/nest/epetro/node_modules/@nestjs/core/router/router-proxy.js:9:17
[Nest] 9228   - 19/04/2021 08:42:22   [HttpExceptionFilter] Http Status: 500 Error Message: {} +13880ms

【问题讨论】:

标签: many-to-many relationship nestjs crud typeorm


【解决方案1】:

问题出在您的 bulkCreateGassStation 方法中。 gasStations.map(this.createGasStations) 不保留调用它的上下文。您可以.bind(this) 并将上下文设置为正确绑定,也可以gasStations.map(station =&gt; this.createStations(station))

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    相关资源
    最近更新 更多