likes
comments
collection
share

NestJS16-HTTP module

作者站长头像
站长
· 阅读数 34

Axios有丰富的特性的HTTP服务端包并被广泛的运用。Nest包装了Axios并且通过内置HttpModule导出。HttpModule导出了HttpService类,它基于Axios方法来处理HTTP请求。这个库也转换HTTP返回结果成Observables

提示:您也可以使用任何Node.jsHTTP服务端库,包括got或者undici

安装

首先我们要安装依赖

$ npm i --save @nestjs/axios axios

开始

一旦安装进程完成了,为了使用HttpService,首先要导入HttpModule

@Module({
  imports: [HttpModule],
  providers: [CatsService],
})
export class CatsModule {}

接着,使用通常的构造器注入HttpService

提示 HttpModuleHttpService是通过@nestjs/axios包导入的

@Injectable()
export class CatsService {
  constructor(private readonly httpService: HttpService) {}

  findAll(): Observable<AxiosResponse<Cat[]>> {
    return this.httpService.get('http://localhost:3000/cats');
  }
}

提示 AxiosResponse是一个接口从axios包($ npm i axios)导入。

所有HttpService方法返回AxiosResponse都被包装成Observable对象。

配置

Axios可以通过这个参数来配置,用于自定义HttpService的行为。在这里阅读更多。为了配置基本Axios实例,当导入它的时候,提供可选参数对象给HttpModuleregister()方法。这个可选的对象会直接传递给Axios构造器。

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

异步配置

当您需要将您的模块参数通过异步配置,使用registerAsync()方法。大多数动态模块,Nest提供几个技术来处理异步配置。

一个技术是使用工厂函数

HttpModule.registerAsync({
  useFactory: () => ({
    timeout: 5000,
    maxRedirects: 5,
  }),
});

像其他的工厂provider,我们的工厂函数可以异步并可以通过inject注入依赖。

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

或者,您们可以使用类来代替工厂配置HttpModule,如下。

HttpModule.registerAsync({
  useClass: HttpConfigService,
});

HttpModule内部构造器实例化了HttpConfigService,使用它来创建一个参数对象。在例子中,HttpConfigService实现了HttpModuleOptionsFactory接口如下。HttpModule将会在类的实例化对象上调用createHttpOptions()方法。

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

如果在HttpModule中您想入复用存在的参数来代替自己新建的复制版本,使用useExisting语句。

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

直接使用Axios

如果您觉得HttpModule.register的参数不能满足您,或者您就想直接访问@nestjs/axios创建的基础的Axios实例,您能够通过HttpService#axiosRef来访问它:

import { catchError, firstValueFrom } from 'rxjs';

@Injectable()
export class CatsService {
  private readonly logger = new Logger(CatsService.name);
  constructor(private readonly httpService: HttpService) {}

  async findAll(): Promise<Cat[]> {
    const { data } = await firstValueFrom(
      this.httpService.get<Cat[]>('http://localhost:3000/cats').pipe(
        catchError((error: AxiosError) => {
          this.logger.error(error.response.data);
          throw 'An error happened!';
        }),
      ),
    );
    return data;
  }
}

提示 阅读RxJS的文档来查看firstValueFromlastValueFrom的不同