Search code examples
typescriptnestjsconfigdropboxdropbox-api

NestJS inject Dropox instantion with config from ConfigService


I have my fileService and I want to add Dropbox file storage for my app.

I want to inject or something like that ready Dropbox instatnion (npm packade Dropbox) from another file (or declare it once in service). The problem is how to inject to that file configService to get accessToken which is need to make instantion

filesService.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') })

I want to declare it once, not in every service funtion which need it.

files.module.ts

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


Solution

  • You could make a custom provider like

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

    And now in your FileService you use @Inject('DropboxService') private readonly dropbox: Dropbox) to inject the created instance.