首页 > 解决方案 > NestJS 使用来自 ConfigService 的配置注入 Dropox 实例

问题描述

我有我的 fileService,我想为我的应用添加 Dropbox 文件存储。

我想从另一个文件中注入或类似的准备好的 Dropbox instatnion (npm packade Dropbox)(或在服务中声明它一次)。问题是如何注入该文件 configService 以获取需要进行实例化的 accessToken

文件服务.ts

@Injectable()
export class FilesService {
  constructor(
    private fileRepo: FilesRepo,
    private usersRepo: UsersRepo,
    private configService: ConfigService,
  ){
    // const dbx = new Dropbox({ accessToken: this.configService.get('DROPBOX_TOKEN') })
    // this.dbx = new Dropbox({ accessToken: this.configService.get('DROPBOX_TOKEN') })
  } 
  //private dbx = new Dropbox({ accessToken: this.configService.get('DROPBOX_TOKEN') })

我想声明一次,而不是在每个需要它的服务功能中。

文件.module.ts

@Module({
  imports: [
    TypeOrmModule.forFeature([FilesRepo,UsersRepo]),
    MulterModule.register({
      dest: './filesTemp',
    }),
    ConfigModule,
  ],
  providers: [FilesService],
  exports: [FilesService],
  controllers: [FilesController]
})
export class FilesModule {}

标签: typescriptnestjsconfigdropboxdropbox-api

解决方案


您可以制作一个自定义提供程序,例如

{
  provide: 'DropboxService',
  inject: [ConfigService],
  useFactory: (config: ConfigService) => {
    return new Dropbox({ accessToken: config.get('DROPBOX_TOKEN') });
  }
}

现在在您FileService使用@Inject('DropboxService') private readonly dropbox: Dropbox)注入创建的实例。


推荐阅读