restql 1.1.6 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -1,157 +1,15 @@
1
1
  'use strict';
2
2
 
3
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
3
+ var cloneDeep = require('lodash/cloneDeep');
4
+ var merge = require('lodash/merge');
5
+ var axios = require('axios');
6
+ var md5 = require('md5');
7
+ var isURL = require('validator/lib/isURL');
4
8
 
5
- var _regeneratorRuntime = _interopDefault(require('babel-runtime/regenerator'));
6
- var cloneDeep = _interopDefault(require('lodash/cloneDeep'));
7
- var merge = _interopDefault(require('lodash/merge'));
8
- var axios = _interopDefault(require('axios'));
9
- var md5 = _interopDefault(require('md5'));
10
- var UrlRegex = _interopDefault(require('url-regex'));
11
-
12
- var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
13
- return typeof obj;
14
- } : function (obj) {
15
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
16
- };
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
- var asyncToGenerator = function (fn) {
27
- return function () {
28
- var gen = fn.apply(this, arguments);
29
- return new Promise(function (resolve, reject) {
30
- function step(key, arg) {
31
- try {
32
- var info = gen[key](arg);
33
- var value = info.value;
34
- } catch (error) {
35
- reject(error);
36
- return;
37
- }
38
-
39
- if (info.done) {
40
- resolve(value);
41
- } else {
42
- return Promise.resolve(value).then(function (value) {
43
- step("next", value);
44
- }, function (err) {
45
- step("throw", err);
46
- });
47
- }
48
- }
49
-
50
- return step("next");
51
- });
52
- };
53
- };
54
-
55
-
56
-
57
-
58
-
59
-
60
-
61
-
62
-
63
- var defineProperty = function (obj, key, value) {
64
- if (key in obj) {
65
- Object.defineProperty(obj, key, {
66
- value: value,
67
- enumerable: true,
68
- configurable: true,
69
- writable: true
70
- });
71
- } else {
72
- obj[key] = value;
73
- }
74
-
75
- return obj;
76
- };
77
-
78
- var _extends = Object.assign || function (target) {
79
- for (var i = 1; i < arguments.length; i++) {
80
- var source = arguments[i];
81
-
82
- for (var key in source) {
83
- if (Object.prototype.hasOwnProperty.call(source, key)) {
84
- target[key] = source[key];
85
- }
86
- }
87
- }
88
-
89
- return target;
90
- };
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
- var slicedToArray = function () {
113
- function sliceIterator(arr, i) {
114
- var _arr = [];
115
- var _n = true;
116
- var _d = false;
117
- var _e = undefined;
118
-
119
- try {
120
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
121
- _arr.push(_s.value);
122
-
123
- if (i && _arr.length === i) break;
124
- }
125
- } catch (err) {
126
- _d = true;
127
- _e = err;
128
- } finally {
129
- try {
130
- if (!_n && _i["return"]) _i["return"]();
131
- } finally {
132
- if (_d) throw _e;
133
- }
134
- }
135
-
136
- return _arr;
137
- }
138
-
139
- return function (arr, i) {
140
- if (Array.isArray(arr)) {
141
- return arr;
142
- } else if (Symbol.iterator in Object(arr)) {
143
- return sliceIterator(arr, i);
144
- } else {
145
- throw new TypeError("Invalid attempt to destructure non-iterable instance");
146
- }
147
- };
148
- }();
149
-
150
- // External Packages
151
9
  /**
152
10
  * @constant {Object} responses The responses to cache.
153
11
  */
154
- var responses = {};
12
+ const responses = {};
155
13
 
156
14
  /**
157
15
  * Fetches a resource based on its options, if not cached.
@@ -160,46 +18,16 @@ var responses = {};
160
18
  * @param {Object} options The options to bypass.
161
19
  * @returns {Promise<Object>} A promise which resolves into an object.
162
20
  */
163
- var fetchResource = (function () {
164
- var _ref = asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(resource, options) {
165
- var key;
166
- return _regeneratorRuntime.wrap(function _callee$(_context) {
167
- while (1) {
168
- switch (_context.prev = _context.next) {
169
- case 0:
170
- key = md5(resource + '-' + JSON.stringify(options));
171
-
172
-
173
- if (!(key in responses)) {
174
- responses[key] = axios(resource, options).then(function (response) {
175
- responses[key] = response;
176
-
177
- return response;
178
- });
179
- }
180
-
181
- return _context.abrupt('return', responses[key]);
182
-
183
- case 3:
184
- case 'end':
185
- return _context.stop();
186
- }
187
- }
188
- }, _callee, this);
189
- }));
190
-
191
- function fetchResource(_x, _x2) {
192
- return _ref.apply(this, arguments);
21
+ async function fetchResource(resource, options) {
22
+ const key = md5(`${resource}-${JSON.stringify(options)}`);
23
+ if (!(key in responses)) {
24
+ responses[key] = axios(resource, options).then(response => {
25
+ responses[key] = response;
26
+ return response;
27
+ });
193
28
  }
194
-
195
- return fetchResource;
196
- })();
197
-
198
- // External Packages
199
- /**
200
- * @constant {Object} urlRegex The URL regex to test.
201
- */
202
- var urlRegex = UrlRegex({ exact: true });
29
+ return responses[key];
30
+ }
203
31
 
204
32
  /**
205
33
  * Determines whether or not a resource is valid.
@@ -208,28 +36,27 @@ var urlRegex = UrlRegex({ exact: true });
208
36
  * @returns {boolean} Whether or not a resource is valid.
209
37
  */
210
38
  function isResource(resource) {
211
- return urlRegex.test(resource);
39
+ return isURL(resource);
212
40
  }
213
41
 
214
42
  /**
215
43
  * @constant {string} PROP_DELIMITER The delimiter of a property.
216
44
  */
217
- var PROP_DELIMITER = '.';
45
+ const PROP_DELIMITER = '.';
218
46
 
219
47
  /**
220
48
  * @constant {RegExp} REGEX_PROP_IS_ARR_IS_OPT Determines whether or not a property is an array and/or is optional.
221
49
  */
222
- var REGEX_PROP_IS_ARR_IS_OPT = /^([^[\]?]+)(\[])?(\?)?$/;
50
+ const REGEX_PROP_IS_ARR_IS_OPT = /^([^[\]?]+)(\[])?(\?)?$/;
223
51
 
224
52
  /**
225
53
  * @constant {Object} constants The constants of the library.
226
54
  */
227
- var constants = Object.freeze({
228
- PROP_DELIMITER: PROP_DELIMITER,
229
- REGEX_PROP_IS_ARR_IS_OPT: REGEX_PROP_IS_ARR_IS_OPT
55
+ const constants = Object.freeze({
56
+ PROP_DELIMITER,
57
+ REGEX_PROP_IS_ARR_IS_OPT
230
58
  });
231
59
 
232
- // Internal Packages
233
60
  /**
234
61
  * Gets the parsed properties from an object.
235
62
  *
@@ -239,36 +66,22 @@ var constants = Object.freeze({
239
66
  * @throws {RuntimeError} If a property could not be got.
240
67
  */
241
68
  function objectGet(obj, props) {
242
- var nextPropsArr = props.split(constants.PROP_DELIMITER);
243
-
244
- var _ref = constants.REGEX_PROP_IS_ARR_IS_OPT.exec(nextPropsArr.shift()) || [],
245
- _ref2 = slicedToArray(_ref, 4),
246
- prop = _ref2[1],
247
- isArr = _ref2[2],
248
- isOpt = _ref2[3];
249
-
250
- var nextProps = nextPropsArr.join(constants.PROP_DELIMITER);
251
-
69
+ const nextPropsArr = props.split(constants.PROP_DELIMITER);
70
+ const [, prop, isArr, isOpt] = constants.REGEX_PROP_IS_ARR_IS_OPT.exec(nextPropsArr.shift()) || [];
71
+ const nextProps = nextPropsArr.join(constants.PROP_DELIMITER);
252
72
  if (!prop) {
253
73
  return obj;
254
74
  }
255
-
256
75
  if (!(prop in obj)) {
257
76
  if (isOpt) {
258
77
  return isArr ? [] : null;
259
78
  }
260
-
261
- throw new Error('RuntimeError: could not get property `' + prop + '`');
79
+ throw new Error(`RuntimeError: could not get property \`${prop}\``);
262
80
  }
263
-
264
- var nextObjs = obj[prop];
265
-
266
- return isArr ? nextObjs.map(function (nextObj) {
267
- return objectGet(nextObj, nextProps);
268
- }) : objectGet(nextObjs, nextProps);
81
+ const nextObjs = obj[prop];
82
+ return isArr ? nextObjs.map(nextObj => objectGet(nextObj, nextProps)) : objectGet(nextObjs, nextProps);
269
83
  }
270
84
 
271
- // Internal Packages
272
85
  /**
273
86
  * Sets the parsed properties to an object.
274
87
  *
@@ -277,26 +90,17 @@ function objectGet(obj, props) {
277
90
  * @returns {Object} An object.
278
91
  */
279
92
  function objectSet(data, props) {
280
- var nextPropsArr = props.split(constants.PROP_DELIMITER);
281
-
282
- var _ref = constants.REGEX_PROP_IS_ARR_IS_OPT.exec(nextPropsArr.shift()) || [],
283
- _ref2 = slicedToArray(_ref, 3),
284
- prop = _ref2[1],
285
- isArr = _ref2[2];
286
-
287
- var nextProps = nextPropsArr.join(constants.PROP_DELIMITER);
288
-
93
+ const nextPropsArr = props.split(constants.PROP_DELIMITER);
94
+ const [, prop, isArr] = constants.REGEX_PROP_IS_ARR_IS_OPT.exec(nextPropsArr.shift()) || [];
95
+ const nextProps = nextPropsArr.join(constants.PROP_DELIMITER);
289
96
  if (!prop) {
290
97
  return data;
291
98
  }
292
-
293
- return defineProperty({}, prop, isArr ? data.map(function (nextData) {
294
- return objectSet(nextData, nextProps);
295
- }) : objectSet(data, nextProps));
99
+ return {
100
+ [prop]: isArr ? data.map(nextData => objectSet(nextData, nextProps)) : objectSet(data, nextProps)
101
+ };
296
102
  }
297
103
 
298
- // External Packages
299
- // Internal Packages
300
104
  /**
301
105
  * Resolves the nested-linked resources of a RESTful API.
302
106
  *
@@ -307,157 +111,35 @@ function objectSet(data, props) {
307
111
  * @throws {InvalidArgumentError} If a resource is invalid.
308
112
  * @throws {RuntimeError} If a resource could not be fetched.
309
113
  */
310
- var resolve = (function () {
311
- var _ref = asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(resource, resolver, options) {
312
- var _this = this;
313
-
314
- var response, obj, resourcesObj, resourcesArr, responses;
315
- return _regeneratorRuntime.wrap(function _callee3$(_context3) {
316
- while (1) {
317
- switch (_context3.prev = _context3.next) {
318
- case 0:
319
- if (resource) {
320
- _context3.next = 2;
321
- break;
322
- }
323
-
324
- return _context3.abrupt('return', null);
325
-
326
- case 2:
327
- if (isResource(resource)) {
328
- _context3.next = 4;
329
- break;
330
- }
331
-
332
- throw new Error('InvalidArgumentError: invalid resource `' + resource + '`');
333
-
334
- case 4:
335
- _context3.t0 = cloneDeep;
336
- _context3.next = 7;
337
- return fetchResource(resource, options);
338
-
339
- case 7:
340
- _context3.t1 = _context3.sent;
341
- response = (0, _context3.t0)(_context3.t1);
342
-
343
- if (response.config.validateStatus(response.status)) {
344
- _context3.next = 11;
345
- break;
346
- }
347
-
348
- throw new Error('RuntimeError: could not fetch resource `' + resource + '`');
349
-
350
- case 11:
351
- obj = response.data;
352
-
353
- if (resolver) {
354
- _context3.next = 14;
355
- break;
356
- }
357
-
358
- return _context3.abrupt('return', obj);
359
-
360
- case 14:
361
- resourcesObj = Object.keys(resolver).map(function (props) {
362
- return defineProperty({}, props, objectGet(obj, props));
363
- });
364
- resourcesArr = Object.entries(resourcesObj.reduce(function (result, val) {
365
- return _extends({}, result, val);
366
- }, {}));
367
- _context3.next = 18;
368
- return Promise.all(resourcesArr.map(function () {
369
- var _ref4 = asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref3) {
370
- var _ref5 = slicedToArray(_ref3, 2),
371
- props = _ref5[0],
372
- resources = _ref5[1];
373
-
374
- var nextResolver, data;
375
- return _regeneratorRuntime.wrap(function _callee2$(_context2) {
376
- while (1) {
377
- switch (_context2.prev = _context2.next) {
378
- case 0:
379
- nextResolver = resolver[props];
380
-
381
- if (!Array.isArray(resources)) {
382
- _context2.next = 7;
383
- break;
384
- }
385
-
386
- _context2.next = 4;
387
- return Promise.all(resources.map(function () {
388
- var _ref6 = asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(nextResource) {
389
- return _regeneratorRuntime.wrap(function _callee$(_context) {
390
- while (1) {
391
- switch (_context.prev = _context.next) {
392
- case 0:
393
- return _context.abrupt('return', resolve(nextResource, nextResolver, options));
394
-
395
- case 1:
396
- case 'end':
397
- return _context.stop();
398
- }
399
- }
400
- }, _callee, _this);
401
- }));
402
-
403
- return function (_x5) {
404
- return _ref6.apply(this, arguments);
405
- };
406
- }()));
407
-
408
- case 4:
409
- _context2.t0 = _context2.sent;
410
- _context2.next = 10;
411
- break;
412
-
413
- case 7:
414
- _context2.next = 9;
415
- return resolve(resources, nextResolver, options);
416
-
417
- case 9:
418
- _context2.t0 = _context2.sent;
419
-
420
- case 10:
421
- data = _context2.t0;
422
- return _context2.abrupt('return', [props, data]);
423
-
424
- case 12:
425
- case 'end':
426
- return _context2.stop();
427
- }
428
- }
429
- }, _callee2, _this);
430
- }));
431
-
432
- return function (_x4) {
433
- return _ref4.apply(this, arguments);
434
- };
435
- }()));
436
-
437
- case 18:
438
- responses = _context3.sent;
439
- return _context3.abrupt('return', responses.reduce(function (result, _ref7) {
440
- var _ref8 = slicedToArray(_ref7, 2),
441
- props = _ref8[0],
442
- data = _ref8[1];
443
-
444
- return merge(result, objectSet(data, props));
445
- }, obj));
446
-
447
- case 20:
448
- case 'end':
449
- return _context3.stop();
450
- }
451
- }
452
- }, _callee3, this);
453
- }));
454
-
455
- function resolve(_x, _x2, _x3) {
456
- return _ref.apply(this, arguments);
114
+ async function resolve(resource, resolver, options) {
115
+ if (!resource) {
116
+ return null;
457
117
  }
458
-
459
- return resolve;
460
- })();
118
+ if (!isResource(resource)) {
119
+ throw new Error(`InvalidArgumentError: invalid resource \`${resource}\``);
120
+ }
121
+ const response = cloneDeep(await fetchResource(resource, options));
122
+ if (!response.config.validateStatus(response.status)) {
123
+ throw new Error(`RuntimeError: could not fetch resource \`${resource}\``);
124
+ }
125
+ const obj = response.data;
126
+ if (!resolver) {
127
+ return obj;
128
+ }
129
+ const resourcesObj = Object.keys(resolver).map(props => ({
130
+ [props]: objectGet(obj, props)
131
+ }));
132
+ const resourcesArr = Object.entries(resourcesObj.reduce((result, val) => ({
133
+ ...result,
134
+ ...val
135
+ }), {}));
136
+ const responses = await Promise.all(resourcesArr.map(async ([props, resources]) => {
137
+ const nextResolver = resolver[props];
138
+ const data = Array.isArray(resources) ? await Promise.all(resources.map(async nextResource => resolve(nextResource, nextResolver, options))) : await resolve(resources, nextResolver, options);
139
+ return [props, data];
140
+ }));
141
+ return responses.reduce((result, [props, data]) => merge(result, objectSet(data, props)), obj);
142
+ }
461
143
 
462
144
  /**
463
145
  * Determines whether or not an object is valid.
@@ -466,10 +148,9 @@ var resolve = (function () {
466
148
  * @returns {boolean} Whether or not an object is valid.
467
149
  */
468
150
  function isObject(obj) {
469
- return obj !== null && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && !Array.isArray(obj);
151
+ return obj !== null && typeof obj === 'object' && !Array.isArray(obj);
470
152
  }
471
153
 
472
- // Internal Packages
473
154
  /**
474
155
  * Determines whether or not a resolver is valid.
475
156
  *
@@ -480,21 +161,13 @@ function isResolver(resolver) {
480
161
  if (!resolver) {
481
162
  return true;
482
163
  }
483
-
484
- var keys = Object.keys(resolver);
485
-
164
+ const keys = Object.keys(resolver);
486
165
  if (!keys.length) {
487
166
  return false;
488
167
  }
489
-
490
- return keys.map(function (key) {
491
- return !key.startsWith(constants.PROP_DELIMITER) && !key.endsWith(constants.PROP_DELIMITER) && isResolver(resolver[key]);
492
- }).reduce(function (result, val) {
493
- return result && val;
494
- }, true);
168
+ return keys.map(key => !key.startsWith(constants.PROP_DELIMITER) && !key.endsWith(constants.PROP_DELIMITER) && isResolver(resolver[key])).reduce((result, val) => result && val, true);
495
169
  }
496
170
 
497
- // Internal Packages
498
171
  /**
499
172
  * Resolves the nested-linked resources of a RESTful API.
500
173
  *
@@ -505,44 +178,14 @@ function isResolver(resolver) {
505
178
  * @throws {InvalidArgumentError} If a resolver is invalid.
506
179
  * @throws {InvalidArgumentError} If an options are invalid.
507
180
  */
508
- var restql = (function () {
509
- var _ref = asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(resource, resolver) {
510
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
511
- return _regeneratorRuntime.wrap(function _callee$(_context) {
512
- while (1) {
513
- switch (_context.prev = _context.next) {
514
- case 0:
515
- if (!(!isObject(resolver) || !isResolver(resolver))) {
516
- _context.next = 2;
517
- break;
518
- }
519
-
520
- throw new Error('InvalidArgumentError: invalid resolver `' + JSON.stringify(resolver) + '`');
521
-
522
- case 2:
523
- if (isObject(options)) {
524
- _context.next = 4;
525
- break;
526
- }
527
-
528
- throw new Error('InvalidArgumentError: invalid options `' + JSON.stringify(options) + '`');
529
-
530
- case 4:
531
- return _context.abrupt('return', resolve(resource, resolver, options));
532
-
533
- case 5:
534
- case 'end':
535
- return _context.stop();
536
- }
537
- }
538
- }, _callee, this);
539
- }));
540
-
541
- function restql(_x2, _x3) {
542
- return _ref.apply(this, arguments);
181
+ async function restql(resource, resolver, options = {}) {
182
+ if (!isObject(resolver) || !isResolver(resolver)) {
183
+ throw new Error(`InvalidArgumentError: invalid resolver \`${JSON.stringify(resolver)}\``);
543
184
  }
544
-
545
- return restql;
546
- })();
185
+ if (!isObject(options)) {
186
+ throw new Error(`InvalidArgumentError: invalid options \`${JSON.stringify(options)}\``);
187
+ }
188
+ return resolve(resource, resolver, options);
189
+ }
547
190
 
548
191
  module.exports = restql;