Skip to content

jasonraimondi/nestjs-axios-promise

Repository files navigation

Nest.js Axios Promise

GitHub Workflow Status Test Coverage Maintainability GitHub package.json version NPM Downloads

A thin wrapper around Axios for Nest.js using Promises, because the @nestjs/axios package returns an observable. See #why

Install

pnpm add nestjs-axios-promise

Usage

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);
  }
}

Custom Config

@Module({
  imports: [
    AxiosModule.register({
      baseURL: "https://example.com",
      headers: {
        "X-My-Header": "Is a value!",
      },
    }),
  ],
})
export class AppModule {}

Why

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;
  }
}

About

A thin wrapper around Axios for Nest.js using Promises, because the @nestjs/axios package returns an observable.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project