-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.js
273 lines (207 loc) · 6.45 KB
/
api.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/**
* API Helper
*
* @author Mohammad Fares <[email protected]>
*/
/**
* Make an API call
*
* @param {String} method GET, POST, PUT, DELETE
* @param {String} endpoint
* @param {Object} params query or body params (default: {})
* @param {Boolean} showSpinner show the loading spinner (default: true)
* @return {Promise} reject when the request is failed or has errors
*/
function call(method, endpoint, params, showSpinner) {
endpoint = pathReplace(endpoint, params);
// Default value for showSpinner
if (typeof showSpinner === 'undefined') {
showSpinner = true;
}
// Default value for params
if (typeof params === 'undefined') {
params = {};
}
return new Promise(function(resolve, reject) {
var url = di.config.getBaseURL() + endpoint + '?' + di.querystring.encode(params);
var options = {
method: method,
url: url,
headers: {
'Authorization': 'Basic ' + di.config.getAuthString(),
'Content-Type': 'application/json'
},
body: params,
json: true
};
// Show a loading spinner
if (showSpinner) {
var spinner = di.ora({
text: 'loading',
color: 'yellow'
}).start();
}
// Make the request
di.request(options, function (error, response, body) {
// Stop the loading spinner
if (showSpinner) {
spinner.stop();
}
if (error) {
return reject(error);
}
// Failed
if (!(200 <= response.statusCode && response.statusCode < 300)) {
if (di.is.json(body)) {
var errorMessage = '';
// Invalid input
if (di.is.propertyDefined(body, 'errors') && di.is.not.empty(body.errors)) {
var errors = di.lodash.map(body.errors, function(value, key) {
return key + ': ' + value;
});
errorMessage = errors.join('\n');
}
// Other errors
if (di.is.propertyDefined(body, 'errorMessages') && di.is.not.empty(body.errorMessages)) {
errorMessage = body.errorMessages.join();
}
return reject(new Error(errorMessage));
}
return reject(new Error('The request is failed with: ' + response.statusCode));
}
resolve(body);
});
});
}
/**
* To replace url's placeholders with their values,
* and delete the replaced parameters from the passed object
*
* @param {String} endpoint
* @param {Object} params
* @return {String}
*/
function pathReplace(endpoint, params) {
for (var i in params) {
var value = params[i];
var pattern = null;
// Param at the middle
pattern = new RegExp('/:' + i + '/');
if (pattern.test(endpoint)) {
endpoint = endpoint.replace(pattern, '/' + value + '/');
delete params[i];
}
// Param at the end
pattern = new RegExp('/:' + i + '$');
if (pattern.test(endpoint)) {
endpoint = endpoint.replace(pattern, '/' + value);
delete params[i];
}
}
return endpoint;
}
/**
* An alias for call('GET', endpoint, params)
*
* @param {String} endpoint
* @param {Object} params
* @param {Boolean} showSpinner show the loading spinner (default: true)
* @return {Promise} reject when the request is failed or has errors
*/
module.exports.get = module.exports.GET = function(endpoint, params, showSpinner) {
return call('GET', endpoint, params, showSpinner);
};
/**
* An alias for call('POST', endpoint, params)
*
* @param {String} endpoint
* @param {Object} params
* @param {Boolean} showSpinner show the loading spinner (default: true)
* @return {Promise} reject when the request is failed or has errors
*/
module.exports.post = module.exports.POST = function(endpoint, params, showSpinner) {
return call('POST', endpoint, params, showSpinner);
};
/**
* An alias for call('PUT', endpoint, params)
*
* @param {String} endpoint
* @param {Object} params
* @param {Boolean} showSpinner show the loading spinner (default: true)
* @return {Promise} reject when the request is failed or has errors
*/
module.exports.put = module.exports.PUT = function(endpoint, params, showSpinner) {
return call('PUT', endpoint, params, showSpinner);
};
/**
* An alias for call('DELETE', endpoint, params)
*
* @param {String} endpoint
* @param {Object} params
* @param {Boolean} showSpinner show the loading spinner (default: true)
* @return {Promise} reject when the request is failed or has errors
*/
module.exports.delete = module.exports.DELETE = function(endpoint, params, showSpinner) {
return call('DELETE', endpoint, params, showSpinner);
};
/**
* Make bulk requests
*
* @param {Object|Array} requests {key: {method, endpoint, params}, ..} or
* [{method, endpoint, params}, ...]
* @param {Boolean} showSpinner show the loading spinner (default: true)
* @return {Promise}
*/
module.exports.bulk = function(requests) {
return new Promise(function(resolve, reject) {
// Default value for showSpinner
if (typeof showSpinner === 'undefined') {
showSpinner = true;
}
// Show a loading spinner
if (showSpinner) {
var spinner = di.ora({
text: 'loading',
color: 'yellow'
}).start();
}
/**
* To be called when the requests are finished
*
* @param {Object|Null} error
* @param {Array|Object} results
*/
var doneCallback = function(error, results) {
// Stop the loading spinner
if (showSpinner) {
spinner.stop();
}
if (error) {
return reject(error);
}
resolve(results);
};
/**
* Execute a request
*
* @param {Object} request
* @param {Function} callback
*/
var execute = function(request, callback) {
var args = [null, request.method, request.endpoint, request.params, false];
var task = di.async.asyncify(call.bind(null,
request.method,
request.endpoint,
request.params,
false));
task(callback);
};
// The requests are passed as an array
if (di.is.array(requests)) {
di.async.map(requests, execute, doneCallback);
// The requests are passed as an object
} else {
di.async.mapValues(requests, di.lodash.rearg(execute, [0, 2, 1]), doneCallback);
}
});
};