Node.js - Axios for Nest support

Introduction

The Axios module for Nest was originally published as part of the @nestjs/common package. This package is a drop-in replacement for the deprecated HttpModule - see https://docs.nestjs.com/techniques/http-moduleexternal link for more information.

Objects

This extension creates the service objects:

  • a NodeJS Delete HttpRequest service object when the delete API of a HttpService is found;
  • a NodeJS Get HttpRequest service object when the get or head APIs of a HttpService is found;
  • a NodeJS Post HttpRequest service object when the post or patch APIs of a HttpService is found;
  • a NodeJS Put HttpRequest service object when the put API of a HttpService is found.

The request API of a HttpService can create four service objects above corresponding the APIs found in its arguments: delete, get, head, post, patch, put. If any API is not found, a NodeJS Get HttpRequest service object is created by default.

Icon Description
NodeJS Delete HttpRequest service
NodeJS Get HttpRequest service
NodeJS Post HttpRequest service
NodeJS Put HttpRequest service
Link type Caller type Callee type
callLink
  • TypeScript Module
  • TypeScript Class
  • TypeScript Method
  • TypeScript Function
  • NodeJS Delete HttpRequest service
  • NodeJS Get HttpRequest service
  • NodeJS Post HttpRequest service
  • NodeJS Put HttpRequest service

Example

Take the following codes:

import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';

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

  create(createCatDto: CreateCatDto): Observable<AxiosResponse<any>> {
    return this.httpService
      .post('http://localhost:3000/cats', createCatDto)
      .pipe(map((response) => response.data));
  }

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

  findOne(id: number): Observable<AxiosResponse<Cat>> {
    return this.httpService
      .get(`http://localhost:3000/cats/${id}`)
      .pipe(map((response) => response.data));
  }

  update(
    id: number,
    updateCatDto: UpdateCatDto,
  ): Observable<AxiosResponse<Cat>> {
    return this.httpService
      .put(`http://localhost:3000/cats/${id}`, updateCatDto)
      .pipe(map((response) => response.data));
  }

  remove(id: number): Observable<AxiosResponse<void>> {
    return this.httpService
      .delete(`http://localhost:3000/cats/${id}`)
      .pipe(map((response) => response.data));
  }
}

In this example, five service objects are created, and five ‘call’ links are also added between these objects and Typescript methods corresponding.