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-module for more information.
Objects
This extension creates the service objects:
- a
NodeJS Delete HttpRequest service
object when thedelete
API of aHttpService
is found; - a
NodeJS Get HttpRequest service
object when theget
orhead
APIs of aHttpService
is found; - a
NodeJS Post HttpRequest service
object when thepost
orpatch
APIs of aHttpService
is found; - a
NodeJS Put HttpRequest service
object when theput
API of aHttpService
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 |
Supported links
Link type | Caller type | Callee type |
---|---|---|
callLink |
|
|
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.