HttpClientFetch.js
2.38 KB
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
const nodeFetch = require('node-fetch')
, ApiError = require('../../ApiError')
;
class HttpClientFetch {
constructor(config) {
this._config = config || {};
}
get headers() {
return this._config.headers || {};
}
get baseURL() {
return this._config.baseURL;
}
get hasBaseUrl() {
return !!this.baseURL;
}
refreshAuthorizationHeader(token) {
if (!this._config.headers) {
this._config.headers = {};
}
this._config.headers['Authorization'] = `Bearer ${token}`;
}
getAgent(url, config) {
const specifiedAgent = config.agent || config.httpsAgent || config.httpAgent || null;
if (specifiedAgent) {
return specifiedAgent;
}
return this._config.httpsAgent || this._config.httpAgent || null;
}
getUrl(url) {
if (!this.hasBaseUrl) {
return url;
} else if (/^http/.test(url)) {
return url;
}
let path;
if (url && url[0] === '/') {
path = url;
} else {
path = `/${url}`;
}
return `${this.baseURL}${path}`;
}
request(req) {
const isJson = req.json === true
, hasData = !!req.data
, url = this.getUrl(req.url)
, headers = this.headers
, config = {
method: req.method,
headers: headers,
timeout: req.timeout || 0,
}
;
if (isJson) {
headers['Content-Type'] = 'application/json';
headers['Accept'] = 'application/json';
if (hasData) {
config.body = JSON.stringify(req.data);
}
} else {
if (hasData) {
config.body = req.data;
}
}
if (req.headers) {
Object.keys(req.headers).forEach(header => {
headers[header] = req.headers[header];
});
}
config.agent = this.getAgent(url, req);
return nodeFetch(url, config)
.then(res => {
if (res.ok) {
return res;
}
throw new ApiError();
})
.then(res => {
const result = {
status: res.status
}
let promise;
if (isJson) {
promise = res.json();
} else {
promise = res.text();
}
return promise.then(data => {
result.data = data;
return result;
});
});
}
}
module.exports.create = (config) => {
return new HttpClientFetch(config);
}
module.exports.request = (req) => {
return new HttpClientFetch().request(req);
}