nestjs 请求数据📚

5,380 阅读1分钟

nestjs 中内置 axios,适配 nestjs 进行了封装。形成一个 HttpModule。

@Module({
  providers: [
    HttpService,
    {
      provide: AXIOS_INSTANCE_TOKEN,
      useValue: Axios,
    },
  ],
  exports: [HttpService],
})
export class HttpModule {
	static register() {}
    static registerAsync() {}
    private static createAsyncProviders() {}
    private static createAsyncOptionsProvider(){}
}
  • HttpService

HttpService 实现了 axios 的各种请求方法和工具函数

export class HttpService {
  constructor(
    @Inject(AXIOS_INSTANCE_TOKEN)
    private readonly instance: AxiosInstance = Axios,
  ) {}
  request(){}
  get(){}
  delete(){}
  head(){}
  post(){}
  put(){}
  patch(){}
  get axiosRef(){}
  private makeObservable(){}
 }

使用 HttpModule 的 HttpService

// 导入HttpModule
import { HttpModule } from '@nestjs/common'
@Module({
  imports: [HttpModule],
  providers: [CatsService],
})
export class CatsModule {}

// 构造函数中注入服务
@Injectable()
export class CatsService {
  constructor(private httpService: HttpService) {
  findAll(): Observable<AxiosResponse<Cat[]>> {
    return this.httpService.get('http://localhost:3000/cats');
  }
}

配置

配置分为同步配置和异步配置

同步配置 register

@Module({
  imports: [
    HttpModule.register({
      timeout: 5000,
      maxRedirects: 5,
      //...
    }),
  ]
})
export class CatsModule {}

请求配置查看: github.com/axios/axios…

异步配置 registerAsync

异步配置注册提供两中形式:

  • 函数式注册
  • class式注册
// 使用 useFactory 工厂函数
HttpModule.registerAsync({
  useFactory: () => ({
    timeout: 5000,
    maxRedirects: 5,
  }),
});

HttpModule.registerAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    timeout: configService.getString('HTTP_TIMEOUT'),
    maxRedirects: configService.getString('HTTP_MAX_REDIRECTS'),
  }),
  inject: [ConfigService],
});

// 使用工厂函数
HttpModule.registerAsync({
  useClass: HttpConfigService,
});

@Injectable()
class HttpConfigService implements HttpModuleOptionsFactory {
  createHttpOptions(): HttpModuleOptions {
    return {
      timeout: 5000,
      maxRedirects: 5,
    };
  }
}

HttpModule.registerAsync({
  imports: [ConfigModule],
  useExisting: ConfigService,
});

小结

  • nestjs 的数据请求在 nestjs 中已经封装好对应的 Module 和 Service 的内容。
  • axios 的配置问题,axios 配置提供了两个中类型的配置: 同步和异步。其中异步配置又分为两种配置方式:函数式, 类式。