A thin wrapper around Axios for Nest.js using Promises, because the @nestjs/axios package returns an observable. See #why
pnpm add nestjs-axios-promise
import { AxiosService } from "./axios.service";
@Module({
imports: [AxiosModule.register()],
providers: [MyCustomService],
})
export class AppModule {}
@Injectable()
export class MyCustomService {
constructor(private readonly http: AxiosService) {}
async doWork() {
const response = await this.http.get("/");
console.log(response);
}
}
@Module({
imports: [
AxiosModule.register({
baseURL: "https://example.com",
headers: {
"X-My-Header": "Is a value!",
},
}),
],
})
export class AppModule {}
Because I find our way using a promise
import { AxiosService } from "nestjs-axios-promise";
@Injectable()
export class CatsService {
private readonly logger = new Logger(CatsService.name);
constructor(private readonly httpService: AxiosService) {}
findAll(): Promise<Cat[]> {
const { data } = await this.httpService
.get<Cat[]>("http://localhost:3000/cats")
.catch((error: AxiosError) => {
this.logger.error(error.response.data);
throw "An error happened!";
});
return data;
}
}
MUCH more preferrable to the nestjs way of using an observable. They're casting their observable to a promise anyways... 🤦
import { catchError, firstValueFrom } from "rxjs";
import { HttpService } from "@nestjs/axios";
@Injectable()
export class CatsService {
private readonly logger = new Logger(CatsService.name);
constructor(private readonly httpService: HttpService) {}
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;
}
}