-
Notifications
You must be signed in to change notification settings - Fork 0
/
solar.js
410 lines (371 loc) · 12.7 KB
/
solar.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/**
* A generic configurable library for making XHR requests
* Author: Sumeet Sarkar
*/
(function (context) {
const global = (typeof context !== 'undefined') ? context : this;
let sBaseUrl = '';
let sAuthConfig = {
/**
* {
* 'basePath': '/my/app/auth/api',
* 'headers': {
* 'AuthConfig-specfic-header' : 'value'
* }
* }
*/
};
let sUnAuthConfig = {
/**
* {
* 'basePath': '/my/app/public/api',
* 'headers': {
* 'UnAuthConfig-specfic-header' : 'value'
* }
* }
*/
};
let sAuthEndpoints = {
/**
* 'api1': {
* 'method': 'GET',
* 'url': '/auth/a/b/c',
* 'responseType': 'json || blob || text || document || arraybuffer',
* 'headers': {
* 'specfic-header' : 'value'
* }
* }
*/
};
let sUnAuthEndpoints = {
/**
* 'api1': {
* 'method': 'GET',
* 'url': '/unauth/a/b/c',
* 'responseType': 'json || blob || text || document || arraybuffer',
* 'headers': {
* 'specfic-header' : 'value'
* }
* }
*/
};
let sCommonHeaders = {
/**
* 'X_COMMON_HEADER_KEY' : 'Header Value'
*/
};
let sCustomRequestGroups = {
/**
* {
* 'group1': {
* parent: 'unAuth',
* config: {
* 'basePath': '/custom/v1',
* 'headers': {
* 'Custom-Group-Header': 'CustomGroupHeaderValue'
* }
* },
* endpoints: {
* 'status': {
* method: 'GET',
* url: '/status',
* responseType: 'json'
* }
* }
* }
*/
};
/**
* extends object properties to parent
* @param {*} parent - object to which props are added
* @param {*} children - objects from which parent extends
* @return {*} parent - with extended properties
*/
function extend(parent, ...children) {
if (parent) {
(children || []).forEach(item => {
for (let prop in item) {
if (item.hasOwnProperty(prop)) {
parent[prop] = item[prop];
}
}
});
}
return parent;
}
function SolarException(message) {
this.message = `SolarException: ${message}`;
this.toString = function () { return this.message; };
}
// prototype function inject to replace strings of pattern {key} with passed key
// TODO: change the String prototype implementation
String.prototype.inject = function i(item) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
let c = item[b];
return typeof c === 'string'
|| typeof c === 'number' ? c : a;
}
);
};
/**
* handles XHR response
* @param {*} xhr - xhr object
* @param {*} method - http method type
* @param {*} successCb - success callback
* @param {*} errorCb - error callback
* @return {*} void
*/
function responseHandler(xhr, method, successCb, errorCb) {
let isSuccess = false;
switch (method.toLowerCase()) {
default: break;
case 'post':
case 'put': isSuccess = (xhr.status === 200
|| xhr.status === 201
|| xhr.status === 202);
break;
case 'get': isSuccess = (xhr.status === 200);
}
isSuccess ?
(successCb && successCb(xhr.response, xhr.status, xhr))
: (errorCb && errorCb(xhr));
}
/**
* Called by execute function to send XHR with final set of params
* @param {*} payload - { method, url, headers, responseType, data, params }
* @param {*} successCb - success callback
* @param {*} errorCb - error callback
* @return {*} void
*/
function makeXHR(payload, successCb, errorCb) {
let data = {};
// switch to method type
switch (payload.method.toLowerCase()) {
default: break;
case 'post':
case 'put': data = JSON.stringify(payload.data || data); break;
case 'get': break;
}
const xhr = new XMLHttpRequest();
// add response type or default to json
xhr.responseType = payload.responseType || 'json';
// extract query params
const params = payload.params || {};
// set query params in url
const url = payload.url.inject(params);
// open xhr
xhr.open(payload.method, url);
// set headers
const payloadHeaders = payload.headers || {};
for (const prop in payloadHeaders) {
if (payloadHeaders.hasOwnProperty(prop)) {
xhr.setRequestHeader(prop, payload.headers[prop]);
}
}
// add readystatechange listener to xhr
xhr.addEventListener('readystatechange', function () {
if (this.readyState === XMLHttpRequest.DONE) {
responseHandler(this, payload.method, successCb, errorCb);
}
});
// xhr send
xhr.send(data);
}
/**
* Prepare final Payload to makeXHR
* @param {*} config - group (auth, unauth, custom) config
* @param {*} endpoint - api endpoint object
* @param {*} payload - { method, url, headers, responseType, data, params }
* @param {*} successCb - success callback
* @param {*} errorCb - error callback
* @return {*} void
*/
function preparePayload(config = {}, endpoint, payload = {}, successCb, errorCb) {
// check for sBaseUrl
if (!sBaseUrl) throw new SolarException('No base url configured !!!');
// check for basePath
const basePath = (config.basePath) ? config.basePath : '';
// check for responseType, defaults to json
const responseType = (config.responseType) ? config.responseType : 'json';
// check for endpoint url
const url = endpoint.url || '';
// compose request url
const requestUrl = `${sBaseUrl}${basePath}${url}`;
// xhr method, defaults to GET if not found
const requestMethod = endpoint.method || 'GET';
// compose consolidated headers
const requestHeaders = extend(
/* empty object */
{},
/* add common headers */
(sCommonHeaders || {}),
/* add config specific headers */
(config.headers || {}),
/* add endpoint specific headers */
(endpoint.headers || {}),
/* add payload specific headers */
/* adding payload headers last to prevent overried duplicates if any */
(payload.headers || {}));
// prepare final payload
payload.method = requestMethod;
payload.url = requestUrl;
payload.headers = requestHeaders;
payload.responseType = responseType;
// make XHR request
makeXHR(payload, successCb, errorCb);
}
/**
* Send Auth/ Unauth XHR request
* @param {*} isAuth - true for auth and false for unauth
* @param {*} api - api key to query from auth/ unauth collection
* @param {*} payload - { headers, responseType, data, params }
* @param {*} successCb - success callback
* @param {*} errorCb - error callback
* @return {*} void
*/
function execute(isAuth, api, payload, successCb, errorCb) {
const collection = isAuth ? sAuthEndpoints : sUnAuthEndpoints;
const config = isAuth ? sAuthConfig : sUnAuthConfig;
// check if api exists in Solar collections
const endpoint = collection[api];
if (!endpoint) throw new SolarException(`No such API found - ${api} !!!`);
preparePayload(config, endpoint, payload, successCb, errorCb);
}
const lib = {
// set base url for all APIs
setBaseUrl: function (url) {
sBaseUrl = url;
return this;
},
// set config for auth APIs
setAuthConfig: function (config) {
sAuthConfig = config;
return this;
},
// set config for unauth APIs
setUnAuthConfig: function (config) {
sUnAuthConfig = config;
return this;
},
// set config json for all authenticated APIs
setAuthenticatedEndpoints: function (endpoints) {
sAuthEndpoints = endpoints;
return this;
},
// set config json for all unauthenticated APIs
setUnAuthenticatedEndpoints: function (endpoints) {
sUnAuthEndpoints = endpoints;
return this;
},
// set common headers needed for all APIs
setCommonHeaders: function (headers) {
sCommonHeaders = headers;
return this;
},
// TODO: add validator script to verify custom groups JSON sturcture
setCustomRequestGroups: function (customReqGroups) {
sCustomRequestGroups = customReqGroups;
return this;
},
// TODO: add validator script to verify individual group JSON
addCustomRequestGroup: function (name, groupConfig) {
if (!sCustomRequestGroups) sCustomRequestGroups = {};
sCustomRequestGroups[name] = groupConfig;
return this;
},
// TODO: work on a way to maintain copy objects
// to prevent mutation of config by accident while processing
getCustomRequestGroups: function () {
// return extend({}, sCustomRequestGroups);
return sCustomRequestGroups;
},
/**
* loads all Solar config at once
* All configs loaded are added to the lib using function chaining,
* this is kepy by design, so as to consider config passed as atomic.
* This ensures all older residual configs if any set by setter functions
* will be replaced with new values in config if present or set to undefined.
* @param {*} config - config json
* @return {*} void
*/
loadConfig: function (config) {
if (!config) throw new SolarException('Solar config is undefined !!!');
this.setBaseUrl(config.baseUrl)
.setAuthenticatedEndpoints(config.authEndpoints)
.setUnAuthenticatedEndpoints(config.unAuthEndpoints)
.setCommonHeaders(config.commonHeaders)
.setAuthConfig(config.authConfig)
.setUnAuthConfig(config.unAuthConfig)
.setCustomRequestGroups(config.customRequestGroups);
return this;
},
// curried functions for auth and unauth XHR requests
executeAuth: execute.bind(this, true),
executeUnAuth: execute.bind(this, false),
/**
* Prepare final Payload to makeXHR
* @param {*} group - group (auth, unauth, custom) config
* @param {*} api - api name
* @param {*} payload - { headers, responseType, data, params }
* @param {*} successCb - success callback
* @param {*} errorCb - error callback
* @return {*} void
*/
executeCustom: function (group, api, payload, successCb, errorCb) {
const customGroups = this.getCustomRequestGroups();
if (!group || !api) throw new SolarException('Group or API name cannot be undefined !!!');
if (!customGroups[group]) throw new SolarException(`No such group - "${group}" in custom request groups !!!`);
const requestGroup = customGroups[group];
const endpoints = requestGroup.endpoints;
if (!endpoints) throw new SolarException(`No endpoints in group - "${group}"`);
const endpoint = endpoints[api];
if (!endpoint) throw new SolarException(`No such api "${api}" in group - "${group}" !!!`);
// make copy of the group config
const groupConfig = extend({}, requestGroup.config || {});
const parent = requestGroup.parent;
if (parent) {
let addOnConfig;
switch (parent.toLowerCase()) {
default: break;
case 'auth': addOnConfig = sAuthConfig; break;
case 'unauth': addOnConfig = sUnAuthConfig; break;
}
if (addOnConfig) {
// prefix parent basePath to the group basePath
groupConfig.basePath = `${(addOnConfig.basePath || '')}${groupConfig.basePath}`;
// extend parent headers to the group headers
groupConfig.headers = extend({}, (addOnConfig.headers || {}), groupConfig.headers);
}
}
preparePayload(groupConfig, endpoint, payload, successCb, errorCb);
},
/**
* @param {*} payload - { method, url, headers, responseType, data, params }
* @param {*} successCb - success callback
* @param {*} errorCb - error callback
* @return {*} void
*/
request: function (payload, successCb, errorCb) {
if (!payload) throw new SolarException('Payload cannot be empty !!!');
if (!payload.method) throw new SolarException('Method cannot be empty !!!');
if (!payload.url) throw new SolarException('Url cannot be empty !!!');
makeXHR(payload, successCb, errorCb);
},
// console logs all the configs setup for the library
info: function () {
console.log('Solar Config ---------------');
console.log(sBaseUrl);
console.log(sAuthEndpoints);
console.log(sAuthEndpoints);
console.log(sUnAuthEndpoints);
console.log(sAuthConfig);
console.log(sUnAuthConfig);
console.log(sCommonHeaders);
console.log(sCustomRequestGroups);
console.log('----------------------------');
}
};
// expose to global property $olar
global.$olar = lib;
}(window) );