-
Notifications
You must be signed in to change notification settings - Fork 18
/
fetch.js
208 lines (194 loc) · 6.65 KB
/
fetch.js
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import querystring from 'querystring';
import fetch from 'cross-fetch';
import { btoa, removeUndefined } from '../../utils/index';
/**
* To perform fetch request
* @param {Object} args
* @param {String} args.method
* @param {String} args.path
* @param {Object} args.params
* @param {Object} args.body
* @param {Object} args.headers
* @param {boolean} args.isSuggestionsAPI
* @param {number} args.httpRequestTimeout - Timeout duration in milliseconds
*/
function fetchRequest(args) {
return new Promise((resolve, reject) => {
const parsedArgs = removeUndefined(args);
try {
const {
method,
path,
params,
body,
isRSAPI,
isSuggestionsAPI,
isMongoRequest = false,
httpRequestTimeout = 0, // Default timeout is 0 (no timeout)
} = parsedArgs;
const app = isSuggestionsAPI ? '.suggestions' : this.app;
let bodyCopy = body;
const contentType = path.endsWith('msearch') || path.endsWith('bulk')
? 'application/x-ndjson'
: 'application/json';
const headers = Object.assign(
{},
{
Accept: 'application/json',
'Content-Type': contentType,
},
args.headers,
this.headers,
);
const timestamp = Date.now();
if (this.credentials) {
headers.Authorization = `Basic ${btoa(this.credentials)}`;
}
const requestOptions = {
method,
headers,
};
if (Array.isArray(bodyCopy)) {
let arrayBody = '';
bodyCopy.forEach((item) => {
arrayBody += JSON.stringify(item);
arrayBody += '\n';
});
bodyCopy = arrayBody;
} else {
bodyCopy = JSON.stringify(bodyCopy) || {};
}
if (Object.keys(bodyCopy).length !== 0) {
requestOptions.body = bodyCopy;
}
const handleTransformRequest = (res) => {
if (
this.transformRequest
&& typeof this.transformRequest === 'function'
) {
const transformRequestPromise = this.transformRequest(res);
return transformRequestPromise instanceof Promise
? transformRequestPromise
: Promise.resolve(transformRequestPromise);
}
return Promise.resolve(res);
};
let responseHeaders = {};
let paramsString = '';
if (params) {
paramsString = `?${querystring.stringify(params)}`;
}
const finalURL = isMongoRequest
? `${this.protocol}://${this.url}`
: `${this.protocol}://${this.url}/${app}/${path}${paramsString}`;
return handleTransformRequest(
Object.assign(
{},
{
url: finalURL,
},
requestOptions,
),
)
.then((ts) => {
const transformedRequest = Object.assign({}, ts);
const { url } = transformedRequest;
delete transformedRequest.url;
const controller = new AbortController();
const { signal } = controller;
const fetchPromise = fetch(
url || finalURL,
Object.assign({}, transformedRequest, {
// apply timestamp header for RS API
headers:
isRSAPI && !isMongoRequest
? Object.assign({}, transformedRequest.headers, {
'x-timestamp': new Date().getTime(),
})
: transformedRequest.headers,
signal, // Attach the abort signal to the fetch request
}),
);
const timeoutPromise = new Promise((_, rejectTP) => {
if (httpRequestTimeout > 0) {
setTimeout(() => {
rejectTP(new Error('Request timeout'));
controller.abort();
}, httpRequestTimeout);
}
});
return Promise.race([fetchPromise, timeoutPromise])
.then((res) => {
if (res.status >= 500) {
return reject(res);
}
responseHeaders = res.headers;
return res
.json()
.then((data) => {
if (res.status >= 400) {
return reject(res);
}
if (data && data.error) {
return reject(data);
}
// Handle error from RS API RESPONSE
if (
isRSAPI
&& data
&& Object.prototype.toString.call(data) === '[object Object]'
) {
if (body && body.query && body.query instanceof Array) {
let errorResponses = 0;
const allResponses = body.query.filter(
q => q.execute || q.execute === undefined,
).length;
if (data) {
Object.keys(data).forEach((key) => {
if (
data[key]
&& Object.prototype.hasOwnProperty.call(
data[key],
'error',
)
&& !!data[key].error
) {
errorResponses += 1;
}
});
}
// reject only when all responses have an error
if (
errorResponses > 0
&& allResponses === errorResponses
) {
return reject(data);
}
}
}
// Handle error from _msearch response
if (data && data.responses instanceof Array) {
const allResponses = data.responses.length;
const errorResponses = data.responses.filter(entry => Object.prototype.hasOwnProperty.call(entry, 'error')).length;
// reject only when all responses have an error
if (allResponses === errorResponses) {
return reject(data);
}
}
const response = Object.assign({}, data, {
_timestamp: timestamp,
_headers: responseHeaders,
});
return resolve(response);
})
.catch(e => reject(e));
})
.catch(e => reject(e));
})
.catch(err => reject(err));
} catch (e) {
return reject(e);
}
});
}
export default fetchRequest;