【问题标题】:Inject class into Custom Repository将类注入自定义存储库
【发布时间】:2021-08-21 05:53:22
【问题描述】:

我创建了一个名为:S3Service 的类,它负责从 S3 上传和删除对象(很多图像),因为我希望在其他模块中使用“服务”(有更好的名称吗?),我决定创建一个自定义模块:UtilsModule 我希望在其中创建一组可重用的共享类。我设法从我的UtilsModule 导出了这个类。

@Injectable()
export class S3Service {
  constructor(@InjectS3() private readonly client: S3) {}
  async removeObject(): Promise<S3.DeleteObjectOutput> {}
  async uploadObject(): Promise<S3.ManagedUpload.SendData> {}
}
@Module({
  providers: [S3Service],
  exports: [S3Service],
})
export class UtilsModule {}

我确实将这个UtilsModule 导入到应用程序模块中。

@Module({
  imports: [
    // Other modules here
    UtilsModule,
  ],
})
export class AppModule {}

然后将其导入需要从 S3 上传或删除对象的模块中。

@Module({
  imports: [
    // Other modules
    TypeOrmModule.forFeature([ProfileRepository]),
    UtilsModule,
  ],
  controllers: [ProfileController],
  providers: [ProfileService],
})
export class ProfileModule {}

最后使用装饰器 @Inject 将其注入所需的存储库。

@EntityRepository(Profile)
export class ProfileRepository extends Repository<Profile> {
  constructor(
    @Inject() private s3Service: S3Service,
  ) {
    super();
  }
}

在这里我的应用程序确实编译了,但是当我通过 Post 请求调用此服务时,抛出了 Internal Server Error,我开始在此“服务”中使用断点进行调试,但看起来 uploadObject 函数是 undefined.

我读到了thread,显然 TypeORM 存储库不受 DI 的约束,有解决方法吗?然后我应该在存储库中实例化这个类吗?

【问题讨论】:

  • 看到您在存储库中注入服务,我有点担心。这样做是不是一个好习惯。不确定。您可以在存储库中导入存储库。尝试这样做也许会有所帮助。
  • 不熟悉这个constructor(@InjectS3() private readonly client: S3) {}在处理S3的时候是这样导入的吗?
  • 这是一个NPM package,我在存储库中使用它,但我决定将其移出。如果这是一个不好的做法,我可能只是将它注入我的服务并从那里上传对象,我只是认为将它放在存储库中将是一个“更干净”的解决方案代码
  • 是的,您不应该尽可能将服务注入您的存储库。

标签: typescript dependency-injection nestjs


【解决方案1】:

我最终放弃了将服务注入到我的存储库中,因为这被认为是一种不好的做法,而且看起来nest 不允许注入到 TypeORM 存储库类中。

对于一个解决方案,我需要将此S3Service(记得使用Injectable() 装饰器)设置为我的UtilsModule 的提供者并将其导出。

@Module({
  providers: [S3Service],
  exports: [S3Service],
})
export class UtilsModule {}

将其导入AppModule 并导入需要它的模块中。

@Module({
  imports: [
    // Other modules
    UtilsModule,
  ],
})
export class ProfileModule {}

然后我将一个存储库注入到我的服务中并直接访问 db 实体,这实际上清理了我的代码。最后在构造函数中作为依赖使用。

export class ProfileService {
  constructor(
    @InjectRepository(Profile)
    private profileRepository: Repository<Profile>,
    private s3Service: S3Service,
  ) {}
}

【讨论】:

    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2021-01-07
    • 2010-10-11
    • 1970-01-01
    相关资源
    最近更新 更多