|
6 | 6 | [](https://github.com/jasonraimondi/nestjs-axios-promise/releases/latest) |
7 | 7 | [](https://www.npmjs.com/package/nestjs-axios-promise) |
8 | 8 |
|
9 | | -A thin wrapper around [Axios](https://github.com/axios/axios) for [Nest.js](https://github.com/nestjs/nest) using Promises, because the [@nestjs/axios](https://github.com/nestjs/axios) package returns an observable. |
| 9 | +A thin wrapper around [Axios](https://github.com/axios/axios) for [Nest.js](https://github.com/nestjs/nest) using Promises, because the [@nestjs/axios](https://github.com/nestjs/axios) package returns an observable. See [#why](#why) |
10 | 10 |
|
11 | 11 | ## Install |
12 | 12 |
|
@@ -53,3 +53,53 @@ export class MyCustomService { |
53 | 53 | }) |
54 | 54 | export class AppModule {} |
55 | 55 | ``` |
| 56 | + |
| 57 | +### Why |
| 58 | + |
| 59 | +Because I find our way using a promise |
| 60 | + |
| 61 | +```ts |
| 62 | +import { AxiosService } from "nestjs-axios-promise"; |
| 63 | + |
| 64 | +@Injectable() |
| 65 | +export class CatsService { |
| 66 | + private readonly logger = new Logger(CatsService.name); |
| 67 | + |
| 68 | + constructor(private readonly httpService: AxiosService) {} |
| 69 | + |
| 70 | + findAll(): Promise<Cat[]> { |
| 71 | + const { data } = await this.httpService |
| 72 | + .get<Cat[]>("http://localhost:3000/cats") |
| 73 | + .catch((error: AxiosError) => { |
| 74 | + this.logger.error(error.response.data); |
| 75 | + throw "An error happened!"; |
| 76 | + }); |
| 77 | + return data; |
| 78 | + } |
| 79 | +} |
| 80 | +``` |
| 81 | + |
| 82 | +MUCH more preferrable to the nestjs way of using an observable. They're casting their observable to a promise anyways... :facepalm: |
| 83 | + |
| 84 | +```ts |
| 85 | +import { catchError, firstValueFrom } from "rxjs"; |
| 86 | +import { HttpService } from "@nestjs/axios"; |
| 87 | + |
| 88 | +@Injectable() |
| 89 | +export class CatsService { |
| 90 | + private readonly logger = new Logger(CatsService.name); |
| 91 | + constructor(private readonly httpService: HttpService) {} |
| 92 | + |
| 93 | + findAll(): Promise<Cat[]> { |
| 94 | + const { data } = await firstValueFrom( |
| 95 | + this.httpService.get<Cat[]>("http://localhost:3000/cats").pipe( |
| 96 | + catchError((error: AxiosError) => { |
| 97 | + this.logger.error(error.response.data); |
| 98 | + throw "An error happened!"; |
| 99 | + }), |
| 100 | + ), |
| 101 | + ); |
| 102 | + return data; |
| 103 | + } |
| 104 | +} |
| 105 | +``` |
0 commit comments