Skip to content

Commit 2a3de52

Browse files
committed
docs: add why
1 parent 4e48c9e commit 2a3de52

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

README.md

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
[![GitHub package.json version](https://img.shields.io/github/package-json/v/jasonraimondi/nestjs-axios-promise?style=flat-square)](https://github.com/jasonraimondi/nestjs-axios-promise/releases/latest)
77
[![NPM Downloads](https://img.shields.io/npm/dt/nestjs-axios-promise?label=npm%20downloads&style=flat-square)](https://www.npmjs.com/package/nestjs-axios-promise)
88

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)
1010

1111
## Install
1212

@@ -53,3 +53,53 @@ export class MyCustomService {
5353
})
5454
export class AppModule {}
5555
```
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

Comments
 (0)