|
1 | | -import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; |
2 | | -import { from as fromPromise, Observable } from 'rxjs'; |
| 1 | +import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; |
| 2 | +import { defer, Observable } from 'rxjs'; |
| 3 | +import { Inject } from '../decorators'; |
| 4 | +import { AXIOS_INSTANCE_TOKEN } from './http.constants'; |
3 | 5 |
|
4 | 6 | export class HttpService { |
| 7 | + constructor( |
| 8 | + @Inject(AXIOS_INSTANCE_TOKEN) |
| 9 | + private readonly instance: AxiosInstance = axios, |
| 10 | + ) {} |
| 11 | + |
5 | 12 | request<T = any>(config: AxiosRequestConfig): Observable<AxiosResponse<T>> { |
6 | | - return fromPromise(axios.request<T>(config)); |
| 13 | + return defer(() => this.instance.request<T>(config)); |
7 | 14 | } |
8 | 15 |
|
9 | 16 | get<T = any>( |
10 | 17 | url: string, |
11 | 18 | config?: AxiosRequestConfig, |
12 | 19 | ): Observable<AxiosResponse<T>> { |
13 | | - return fromPromise(axios.get<T>(url, config)); |
| 20 | + return defer(() => this.instance.get<T>(url, config)); |
14 | 21 | } |
15 | 22 |
|
16 | 23 | delete<T = any>( |
17 | 24 | url: string, |
18 | 25 | config?: AxiosRequestConfig, |
19 | 26 | ): Observable<AxiosResponse<T>> { |
20 | | - return fromPromise(axios.delete(url, config)); |
| 27 | + return defer(() => this.instance.delete(url, config)); |
21 | 28 | } |
22 | 29 |
|
23 | 30 | head<T = any>( |
24 | 31 | url: string, |
25 | 32 | config?: AxiosRequestConfig, |
26 | 33 | ): Observable<AxiosResponse<T>> { |
27 | | - return fromPromise(axios.head(url, config)); |
| 34 | + return defer(() => this.instance.head(url, config)); |
28 | 35 | } |
29 | 36 |
|
30 | 37 | post<T = any>( |
31 | 38 | url: string, |
32 | 39 | data?, |
33 | 40 | config?: AxiosRequestConfig, |
34 | 41 | ): Observable<AxiosResponse<T>> { |
35 | | - return fromPromise(axios.post(url, data, config)); |
| 42 | + return defer(() => this.instance.post(url, data, config)); |
36 | 43 | } |
37 | 44 |
|
38 | 45 | put<T = any>( |
39 | 46 | url: string, |
40 | 47 | data?, |
41 | 48 | config?: AxiosRequestConfig, |
42 | 49 | ): Observable<AxiosResponse<T>> { |
43 | | - return fromPromise(axios.put(url, data, config)); |
| 50 | + return defer(() => this.instance.put(url, data, config)); |
44 | 51 | } |
45 | 52 |
|
46 | 53 | patch<T = any>( |
47 | 54 | url: string, |
48 | 55 | data?, |
49 | 56 | config?: AxiosRequestConfig, |
50 | 57 | ): Observable<AxiosResponse<T>> { |
51 | | - return fromPromise(axios.patch(url, data, config)); |
| 58 | + return defer(() => this.instance.patch(url, data, config)); |
52 | 59 | } |
53 | 60 |
|
54 | | - get axiosRef() { |
55 | | - return axios as any; |
| 61 | + get axiosRef(): AxiosInstance { |
| 62 | + return this.instance; |
56 | 63 | } |
57 | 64 | } |
0 commit comments