NestJS Axios (@nestjs/axios)

repository·master·Indexed 42 days ago

https://github.com/nestjs/axios

A NestJS module that integrates the Axios HTTP client, transforming standard Axios responses into RxJS Observables. It provides the HttpModule for configuration via register() and registerAsync(), and the HttpService for performing HTTP requests within the NestJS framework. Version 12.0.1.

Tokens
2.9K
Snippets
12
Records
14
Agent score
54%

What's inside NestJS Axios

  1. Overview of the HttpModule

    master
    The HttpModule is a NestJS module that provides Axios-based methods for performing HTTP requests. A key feature of this module is that it transforms standard Axios HTTP responses into RxJS Observables, allowing you to leverage reactive programming patterns within your NestJS applications.
  2. Configure HttpModule synchronously with register()

    master

    Use the register static method to configure the HttpModule with a fixed configuration object. This method allows you to set a global flag to make the module available throughout your entire application. The provided configuration is used to create a custom Axios instance via Axios.create(config) which is then provided under the AXIOS_INSTANCE_TOKEN.

    @Module({
      imports: [HttpModule.register({ 
        global: true, 
        timeout: 5000 
      })],
    })
    export class MyModule {}
  3. Use HttpService to perform HTTP requests

    master

    The HttpService class provides a wrapper around AxiosInstance, converting standard Axios promise-based requests into RxJS Observable streams. This allows you to integrate HTTP calls seamlessly into NestJS reactive patterns.

    All request methods return an Observable<AxiosResponse<T>>. You can use standard RxJS operators (like map, catchError, or switchMap) to handle the response data or errors.

    import { HttpService } from '@nestjs/axios';
    import { map } from 'rxjs';
    
    // Inside a NestJS service or controller
    constructor(private readonly httpService: HttpService) {}
    
    async getData() {
      const { data } = await this.httpService.get('https://api.example.com/data').toPromise();
      return data;
    }
    
    // Or using RxJS operators
    this.httpService.get('https://api.example.com/data').pipe(
      map(response => response.data)
    ).subscribe(data => console.log(data));
  4. Configure HttpModule with static options

    master

    When importing HttpModule, you can provide static configuration using the HttpModuleOptions type. This type extends AxiosRequestConfig, allowing you to pass any standard Axios configuration (like baseURL, timeout, headers, etc.). Additionally, you can set the global property to true to register the module globally within your NestJS application.

    // Example of the shape of HttpModuleOptions
    const options: HttpModuleOptions = {
      baseURL: 'https://api.example.com',
      timeout: 5000,
      global: true,
    };
  5. Configure HttpModule asynchronously with registerAsync()

    master

    Use the registerAsync static method when your HTTP configuration needs to be loaded asynchronously (e.g., from a database or a configuration service). This method supports three patterns for providing options:

    1. useFactory: Provide a factory function that returns the configuration.
    2. useClass: Provide a class that implements HttpModuleOptionsFactory to create the configuration.
    3. useExisting: Use an existing provider to supply the configuration.

    You can also pass imports to resolve dependencies for your factory, set the global flag, or provide extraProviders to be included in the module's provider list.

    @Module({
      imports: [
        HttpModule.registerAsync({
          global: true,
          imports: [ConfigModule],
          useFactory: async (configService: ConfigService) => ({
            timeout: configService.get('HTTP_TIMEOUT'),
          }),
          inject: [ConfigService],
        }),
      ],
    })
    export class MyModule {}
  6. Access the underlying Axios instance via axiosRef

    master

    If you need to access the raw AxiosInstance to use features not explicitly wrapped by HttpService (or to configure interceptors directly), you can use the axiosRef getter.

    const axiosInstance = this.httpService.axiosRef;
  7. Configure HttpModule with asynchronous options

    master

    To configure HttpModule asynchronously (e.g., when options depend on other providers or environment variables), use HttpModuleAsyncOptions. This interface supports several patterns for dynamic configuration:

    • useFactory: A function that returns HttpModuleOptions or a Promise<HttpModuleOptions>. You can specify dependencies to be injected into this factory using the inject array.
    • useClass: A class that implements the HttpModuleOptionsFactory interface.
    • useExisting: An existing provider that implements the HttpModuleOptionsFactory interface.

    Common properties include:

    • inject: An array of providers to be injected into the factory function.
    • extraProviders: Additional providers to be registered alongside the module.
    • global: Set to true to register the module as a global module.
    // Example using useFactory
    HttpModule.registerAsync({
      useFactory: (configService: ConfigService) => ({
        baseURL: configService.get('API_URL'),
        timeout: 1000,
      }),
      inject: [ConfigService],
    });
  8. HttpService API Reference

    master

    The HttpService exposes the following methods, all of which return an Observable. Most methods accept a url, optional data, and an AxiosRequestConfig object.

    request<T = any>(config: AxiosRequestConfig): Observable<AxiosResponse<T>>
    get<T = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T, D>>
    post<T = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T, D>>
    put<T = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T, D>>
    patch<T = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T, D>>
    delete<T = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T, D>>
    head<T = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T, D>>
    
    // Form-specific methods
    postForm<T = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T, D>>
    putForm<T = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T, D>>
    patchForm<T = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T, D>>
    
    // Query method
    query<T = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T, D>>
  9. Import HttpModule and HttpService from @nestjs/axios

    master

    The @nestjs/axios package exports the core components required to integrate Axios into a NestJS application. To use Axios within your NestJS services, you must import and register HttpModule in your module definitions and then inject HttpService into your classes.

    import { HttpModule } from '@nestjs/axios';
    import { HttpService } from '@nestjs/axios';
    import { Module } from '@nestjs/common';
    
    @Module({
      imports: [HttpModule],
      providers: [MyService],
    })
    export class MyModule {}
  10. Implement HttpModuleOptionsFactory for class-based configuration

    master

    If you prefer to use a class to provide your HTTP configuration, implement the HttpModuleOptionsFactory interface. This interface requires a createHttpOptions() method that returns either HttpModuleOptions or a Promise<HttpModuleOptions>.

    import { HttpModuleOptionsFactory, HttpModuleOptions } from '@nestjs/axios';
    
    export class MyHttpConfigFactory implements HttpModuleOptionsFactory {
      createHttpOptions(): HttpModuleOptions {
        return {
          baseURL: 'https://api.example.com',
        };
      }
    }
    
    // Usage in a module
    @Module({
      imports: [
        HttpModule.registerAsync({
          useClass: MyHttpConfigFactory,
        }),
      ],
    })
    export class MyModule {}
  11. Use HTTP_MODULE_OPTIONS to access module configuration

    master

    If you need to access the configuration options passed to the HttpModule during its initialization, you can inject them using the HTTP_MODULE_OPTIONS token.

    @Injectable()
    export class MyService {
      constructor(@Inject(HTTP_MODULE_OPTIONS) private readonly options: HttpModuleOptions) {}
    }