使用nest.js,如何注入具有构造函数的Provider?

Sha*_*oon 3 javascript dependency-injection node.js typescript nestjs

conversations.module.ts有:

@Module({
  imports: [ImageModule, YoutubeModule],
  controllers: [ConversationsController],
  providers: [ConversationsService, ParticipantsService, StreamsService]
})
export class ConversationsModule { }
Run Code Online (Sandbox Code Playgroud)

在我的 中conversations.controller.ts,我有:

@Controller('conversations')
export class ConversationsController {
    constructor(private conversationsService: ConversationsService, private imageService: ImageService, private youtubeService: YoutubeService, private participantsService: ParticipantsService, private streamsService: StreamsService) { }
Run Code Online (Sandbox Code Playgroud)

但我想做的是注入 AWS S3 模块:

const secretsmanager = new S3({ region: 'us-east-1' })
Run Code Online (Sandbox Code Playgroud)

这需要它被实例化。我怎样才能做到这一点?

Jay*_*iel 5

听起来您正在寻找定制提供商。您可以定义一个注入令牌(字符串)并将其提供给带有键provide和键useClass, useValue, 或的对象useFactory,该键确定要注入什么值。对于你的情况,你可以做类似的事情

{
  provide: 'SECRETS_MANAGER',
  useValue: new S3({ region: 'us-east-1' }),
}
Run Code Online (Sandbox Code Playgroud)

现在您可以@Inject()在构造函数中将注入令牌与装饰器一起使用,如下所示

constructor(@Inject('SECRETS_MANAGER') private readonly manager: S3) {}
Run Code Online (Sandbox Code Playgroud)

或者无论类型new S3()返回什么。