restql 1.1.6 → 1.1.8

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,11 @@
1
1
  'use strict';
2
2
 
3
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
3
+ var esToolkit = require('es-toolkit');
4
4
 
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
5
  /**
152
6
  * @constant {Object} responses The responses to cache.
153
7
  */
154
- var responses = {};
8
+ const responses = {};
155
9
 
156
10
  /**
157
11
  * Fetches a resource based on its options, if not cached.
@@ -160,46 +14,16 @@ var responses = {};
160
14
  * @param {Object} options The options to bypass.
161
15
  * @returns {Promise<Object>} A promise which resolves into an object.
162
16
  */
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);
17
+ async function fetchResource(resource, options) {
18
+ const key = `${resource}-${JSON.stringify(options)}`;
19
+ if (!(key in responses)) {
20
+ responses[key] = fetch(resource, options).then(response => {
21
+ responses[key] = response;
22
+ return response;
23
+ });
193
24
  }
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 });
25
+ return responses[key];
26
+ }
203
27
 
204
28
  /**
205
29
  * Determines whether or not a resource is valid.
@@ -208,28 +32,27 @@ var urlRegex = UrlRegex({ exact: true });
208
32
  * @returns {boolean} Whether or not a resource is valid.
209
33
  */
210
34
  function isResource(resource) {
211
- return urlRegex.test(resource);
35
+ return Boolean(URL.parse(resource));
212
36
  }
213
37
 
214
38
  /**
215
39
  * @constant {string} PROP_DELIMITER The delimiter of a property.
216
40
  */
217
- var PROP_DELIMITER = '.';
41
+ const PROP_DELIMITER = '.';
218
42
 
219
43
  /**
220
44
  * @constant {RegExp} REGEX_PROP_IS_ARR_IS_OPT Determines whether or not a property is an array and/or is optional.
221
45
  */
222
- var REGEX_PROP_IS_ARR_IS_OPT = /^([^[\]?]+)(\[])?(\?)?$/;
46
+ const REGEX_PROP_IS_ARR_IS_OPT = /^([^[\]?]+)(\[])?(\?)?$/;
223
47
 
224
48
  /**
225
49
  * @constant {Object} constants The constants of the library.
226
50
  */
227
- var constants = Object.freeze({
228
- PROP_DELIMITER: PROP_DELIMITER,
229
- REGEX_PROP_IS_ARR_IS_OPT: REGEX_PROP_IS_ARR_IS_OPT
51
+ const constants = Object.freeze({
52
+ PROP_DELIMITER,
53
+ REGEX_PROP_IS_ARR_IS_OPT
230
54
  });
231
55
 
232
- // Internal Packages
233
56
  /**
234
57
  * Gets the parsed properties from an object.
235
58
  *
@@ -239,36 +62,22 @@ var constants = Object.freeze({
239
62
  * @throws {RuntimeError} If a property could not be got.
240
63
  */
241
64
  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
-
65
+ const nextPropsArr = props.split(constants.PROP_DELIMITER);
66
+ const [, prop, isArr, isOpt] = constants.REGEX_PROP_IS_ARR_IS_OPT.exec(nextPropsArr.shift()) || [];
67
+ const nextProps = nextPropsArr.join(constants.PROP_DELIMITER);
252
68
  if (!prop) {
253
69
  return obj;
254
70
  }
255
-
256
71
  if (!(prop in obj)) {
257
72
  if (isOpt) {
258
73
  return isArr ? [] : null;
259
74
  }
260
-
261
- throw new Error('RuntimeError: could not get property `' + prop + '`');
75
+ throw new Error(`RuntimeError: could not get property \`${prop}\``);
262
76
  }
263
-
264
- var nextObjs = obj[prop];
265
-
266
- return isArr ? nextObjs.map(function (nextObj) {
267
- return objectGet(nextObj, nextProps);
268
- }) : objectGet(nextObjs, nextProps);
77
+ const nextObjs = obj[prop];
78
+ return isArr ? nextObjs.map(nextObj => objectGet(nextObj, nextProps)) : objectGet(nextObjs, nextProps);
269
79
  }
270
80
 
271
- // Internal Packages
272
81
  /**
273
82
  * Sets the parsed properties to an object.
274
83
  *
@@ -277,26 +86,17 @@ function objectGet(obj, props) {
277
86
  * @returns {Object} An object.
278
87
  */
279
88
  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
-
89
+ const nextPropsArr = props.split(constants.PROP_DELIMITER);
90
+ const [, prop, isArr] = constants.REGEX_PROP_IS_ARR_IS_OPT.exec(nextPropsArr.shift()) || [];
91
+ const nextProps = nextPropsArr.join(constants.PROP_DELIMITER);
289
92
  if (!prop) {
290
93
  return data;
291
94
  }
292
-
293
- return defineProperty({}, prop, isArr ? data.map(function (nextData) {
294
- return objectSet(nextData, nextProps);
295
- }) : objectSet(data, nextProps));
95
+ return {
96
+ [prop]: isArr ? data.map(nextData => objectSet(nextData, nextProps)) : objectSet(data, nextProps)
97
+ };
296
98
  }
297
99
 
298
- // External Packages
299
- // Internal Packages
300
100
  /**
301
101
  * Resolves the nested-linked resources of a RESTful API.
302
102
  *
@@ -307,157 +107,35 @@ function objectSet(data, props) {
307
107
  * @throws {InvalidArgumentError} If a resource is invalid.
308
108
  * @throws {RuntimeError} If a resource could not be fetched.
309
109
  */
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);
110
+ async function resolve(resource, resolver, options) {
111
+ if (!resource) {
112
+ return null;
457
113
  }
458
-
459
- return resolve;
460
- })();
114
+ if (!isResource(resource)) {
115
+ throw new Error(`InvalidArgumentError: invalid resource \`${resource}\``);
116
+ }
117
+ const response = (await fetchResource(resource, options)).clone();
118
+ if (!response.ok) {
119
+ throw new Error(`RuntimeError: could not fetch resource \`${resource}\``);
120
+ }
121
+ const obj = await response.json();
122
+ if (!resolver) {
123
+ return obj;
124
+ }
125
+ const resourcesObj = Object.keys(resolver).map(props => ({
126
+ [props]: objectGet(obj, props)
127
+ }));
128
+ const resourcesArr = Object.entries(resourcesObj.reduce((result, val) => ({
129
+ ...result,
130
+ ...val
131
+ }), {}));
132
+ const responses = await Promise.all(resourcesArr.map(async ([props, resources]) => {
133
+ const nextResolver = resolver[props];
134
+ const data = Array.isArray(resources) ? await Promise.all(resources.map(async nextResource => resolve(nextResource, nextResolver, options))) : await resolve(resources, nextResolver, options);
135
+ return [props, data];
136
+ }));
137
+ return responses.reduce((result, [props, data]) => esToolkit.merge(result, objectSet(data, props)), obj);
138
+ }
461
139
 
462
140
  /**
463
141
  * Determines whether or not an object is valid.
@@ -466,10 +144,9 @@ var resolve = (function () {
466
144
  * @returns {boolean} Whether or not an object is valid.
467
145
  */
468
146
  function isObject(obj) {
469
- return obj !== null && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && !Array.isArray(obj);
147
+ return obj !== null && typeof obj === 'object' && !Array.isArray(obj);
470
148
  }
471
149
 
472
- // Internal Packages
473
150
  /**
474
151
  * Determines whether or not a resolver is valid.
475
152
  *
@@ -480,21 +157,13 @@ function isResolver(resolver) {
480
157
  if (!resolver) {
481
158
  return true;
482
159
  }
483
-
484
- var keys = Object.keys(resolver);
485
-
160
+ const keys = Object.keys(resolver);
486
161
  if (!keys.length) {
487
162
  return false;
488
163
  }
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);
164
+ return keys.map(key => !key.startsWith(constants.PROP_DELIMITER) && !key.endsWith(constants.PROP_DELIMITER) && isResolver(resolver[key])).reduce((result, val) => result && val, true);
495
165
  }
496
166
 
497
- // Internal Packages
498
167
  /**
499
168
  * Resolves the nested-linked resources of a RESTful API.
500
169
  *
@@ -505,44 +174,14 @@ function isResolver(resolver) {
505
174
  * @throws {InvalidArgumentError} If a resolver is invalid.
506
175
  * @throws {InvalidArgumentError} If an options are invalid.
507
176
  */
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);
177
+ async function restql(resource, resolver, options = {}) {
178
+ if (!isObject(resolver) || !isResolver(resolver)) {
179
+ throw new Error(`InvalidArgumentError: invalid resolver \`${JSON.stringify(resolver)}\``);
543
180
  }
544
-
545
- return restql;
546
- })();
181
+ if (!isObject(options)) {
182
+ throw new Error(`InvalidArgumentError: invalid options \`${JSON.stringify(options)}\``);
183
+ }
184
+ return resolve(resource, resolver, options);
185
+ }
547
186
 
548
187
  module.exports = restql;