forked from nest-cloud/nestcloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.client.ts
159 lines (138 loc) · 5.48 KB
/
http.client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import {
HttpException,
Inject,
Injectable,
InternalServerErrorException,
ServiceUnavailableException,
} from '@nestjs/common';
import { ILoadbalance } from '@nestcloud/common';
import { Interceptor } from './interfaces/interceptor.interface';
import { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import axios from 'axios';
import * as LbModule from '@nestcloud/loadbalance';
import { HttpOptions } from './interfaces/http-options.interface';
import { AXIOS_INSTANCE_PROVIDER, HTTP_OPTIONS_PROVIDER } from './http.constants';
import { Brakes, Fallback } from '@nestcloud/brakes';
@Injectable()
export class HttpClient {
private lb: ILoadbalance;
private brakes: Brakes;
private fallback: Fallback;
private interceptors: Interceptor[];
private readonly service: string;
constructor(
@Inject(AXIOS_INSTANCE_PROVIDER) private readonly http: AxiosInstance,
@Inject(HTTP_OPTIONS_PROVIDER) private readonly options: HttpOptions,
) {
this.service = options.service;
}
create(options: HttpOptions = {}) {
return new HttpClient(
axios.create({ ...options }),
options,
);
}
useLb(lb: ILoadbalance) {
this.lb = lb;
return this;
}
useInterceptors(...interceptors: Interceptor[]) {
this.interceptors = interceptors;
this.registerInterceptors();
return this;
}
useBrakes(brakes: Brakes, fallback?: Fallback) {
this.brakes = brakes;
this.fallback = fallback;
}
public async get(url: string, config: AxiosRequestConfig = {}): Promise<AxiosResponse | any> {
return this.request({ method: 'get', url, ...config });
}
public async delete(url: string, config: AxiosRequestConfig = {}): Promise<AxiosResponse | any> {
return this.request({ method: 'delete', url, ...config });
}
public async head(url: string, config: AxiosRequestConfig = {}): Promise<AxiosResponse | any> {
return this.request({ method: 'head', url, ...config });
}
public async post(url: string, data?: any, config: AxiosRequestConfig = {}): Promise<AxiosResponse | any> {
return this.request({ method: 'post', url, data, ...config });
}
public async put(url: string, data?: any, config: AxiosRequestConfig = {}): Promise<AxiosResponse | any> {
return this.request({ method: 'put', url, data, ...config });
}
public async patch(url: string, data?: any, config: AxiosRequestConfig = {}): Promise<AxiosResponse | any> {
return this.request({ method: 'patch', url, data, ...config });
}
public async request(options: AxiosRequestConfig): Promise<AxiosResponse | any> {
if (this.brakes) {
return this.requestWithBrakes(options);
}
return this.doRequest(options);
}
private async requestWithBrakes(options: AxiosRequestConfig): Promise<AxiosResponse | any> {
let e: HttpException = null;
const ref = this.brakes.slave(this.service, this.fallback, async () => {
try {
return await this.doRequest(options);
} catch (error) {
e = error;
if (error instanceof HttpException) {
return;
}
throw e;
}
});
const response = await ref(options);
if (e) {
throw e;
}
return response;
}
public async doRequest(options: AxiosRequestConfig): Promise<AxiosResponse | any> {
let response: AxiosResponse;
if (this.service && this.lb) {
const module: typeof LbModule = require('@nestcloud/loadbalance');
const server = this.lb.choose(this.service);
if (!server) {
throw new InternalServerErrorException(`No available server can handle this request`);
}
response = await new module.HttpDelegate(server).send(this.http, options);
} else if (this.service) {
if (options.url && options.url.charAt(0) !== '/') {
options.url = '/' + options.url;
}
options.url = `http://${this.service}${options.url}`;
response = await this.send(options);
} else {
response = await this.send(options);
}
return response;
}
private registerInterceptors() {
if (this.interceptors) {
this.interceptors.forEach(interceptor => {
this.http.interceptors.request.use(
interceptor.onRequest ? interceptor.onRequest.bind(interceptor) : undefined,
interceptor.onRequestError ? interceptor.onRequestError.bind(interceptor) : undefined,
);
this.http.interceptors.response.use(
interceptor.onResponse ? interceptor.onResponse.bind(interceptor) : undefined,
interceptor.onResponseError ? interceptor.onResponseError.bind(interceptor) : undefined,
);
});
}
}
private async send(config: AxiosRequestConfig): Promise<AxiosResponse> {
try {
return await this.http.request(config);
} catch (e) {
if (e.response) {
throw new HttpException(e.response.data, e.response.status);
}
if (e.request) {
throw new HttpException(e.message, 400);
}
throw new ServiceUnavailableException(e.message);
}
}
}