typescript - NestJS 使用来自 ConfigService 的配置注入 Dropox 实例
问题描述
我有我的 fileService,我想为我的应用添加 Dropbox 文件存储。
我想从另一个文件中注入或类似的准备好的 Dropbox instatnion (npm packade Dropbox)(或在服务中声明它一次)。问题是如何注入该文件 configService 以获取需要进行实例化的 accessToken
@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({
imports: [
TypeOrmModule.forFeature([FilesRepo,UsersRepo]),
MulterModule.register({
dest: './filesTemp',
}),
ConfigModule,
],
providers: [FilesService],
exports: [FilesService],
controllers: [FilesController]
})
export class FilesModule {}
解决方案
您可以制作一个自定义提供程序,例如
{
provide: 'DropboxService',
inject: [ConfigService],
useFactory: (config: ConfigService) => {
return new Dropbox({ accessToken: config.get('DROPBOX_TOKEN') });
}
}
现在在您FileService
使用@Inject('DropboxService') private readonly dropbox: Dropbox)
注入创建的实例。
推荐阅读
- python - 计算 SciPy 三次样条的平滑度
- c - 使用指针交换字符串的第一个字符
- javascript - 如果用户取消覆盖当前输入,则克隆带有值的输入 HTML 元素并将其放回 DOM
- python - 如何在python中编辑输入的文本
- python-3.x - 上述样本的 t-statistic,并在单独的行中显示 t-score 和 p-value
- ios - UIBarButtonItem 文本非常靠近右边缘
- php - Laravel 查询单个列的总和
- graphql - 如何在 Apollo 中打开和关闭轮询?
- c++ - 使用策略模式设计软件的问题
- javascript - 使用 PWA 构建应用程序