rest-client-sdk 6.7.1 → 7.0.0-rc.10

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/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('deep-diff'), require('urijs')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'deep-diff', 'urijs'], factory) :
4
- (global = global || self, factory(global['rest-client-sdk'] = {}, global.diff, global.URI));
5
- }(this, (function (exports, deepDiff, URI) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('urijs'), require('deep-diff')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'urijs', 'deep-diff'], factory) :
4
+ (global = global || self, factory(global['rest-client-sdk'] = {}, global.URI, global.diff));
5
+ }(this, (function (exports, URI, deepDiff) { 'use strict';
6
6
 
7
7
  URI = URI && Object.prototype.hasOwnProperty.call(URI, 'default') ? URI['default'] : URI;
8
8
 
@@ -22,42 +22,6 @@
22
22
  return _typeof(obj);
23
23
  }
24
24
 
25
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
26
- try {
27
- var info = gen[key](arg);
28
- var value = info.value;
29
- } catch (error) {
30
- reject(error);
31
- return;
32
- }
33
-
34
- if (info.done) {
35
- resolve(value);
36
- } else {
37
- Promise.resolve(value).then(_next, _throw);
38
- }
39
- }
40
-
41
- function _asyncToGenerator(fn) {
42
- return function () {
43
- var self = this,
44
- args = arguments;
45
- return new Promise(function (resolve, reject) {
46
- var gen = fn.apply(self, args);
47
-
48
- function _next(value) {
49
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
50
- }
51
-
52
- function _throw(err) {
53
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
54
- }
55
-
56
- _next(undefined);
57
- });
58
- };
59
- }
60
-
61
25
  function _classCallCheck(instance, Constructor) {
62
26
  if (!(instance instanceof Constructor)) {
63
27
  throw new TypeError("Cannot call a class as a function");
@@ -407,450 +371,347 @@
407
371
  return value;
408
372
  }
409
373
 
410
- /* eslint-disable @typescript-eslint/no-unused-vars */
411
- var Serializer = /*#__PURE__*/function () {
412
- function Serializer() {
413
- _classCallCheck(this, Serializer);
414
- }
374
+ /* eslint-disable max-classes-per-file, no-use-before-define */
415
375
 
416
- _createClass(Serializer, [{
417
- key: "normalizeItem",
376
+ /**
377
+ * It's a bit tricky to extends native errors
378
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
379
+ */
380
+ var HttpError = /*#__PURE__*/function (_Error) {
381
+ _inherits(HttpError, _Error);
418
382
 
419
- /**
420
- * convert an entity to a plain javascript object
421
- * @param {object} entity - The entity to convert
422
- * @param {ClassMetadata} classMetadata - the class metadata
423
- * @return {object} the object to serialize
424
- */
425
- value: function normalizeItem(entity, classMetadata) {
426
- return entity;
427
- }
428
- /**
429
- * convert a plain javascript object to string
430
- * @param {object} object - The object to convert to convert
431
- * @param {ClassMetadata} classMetadata - the class metadata
432
- * @return {string} the content of the request
433
- */
383
+ var _super = _createSuper(HttpError);
434
384
 
435
- }, {
436
- key: "encodeItem",
437
- value: function encodeItem(object, classMetadata) {
438
- throw new TypeError('`encodeItem` method must be implemented');
439
- }
440
- /**
441
- * convert an entity to string that will be sent as the request content
442
- * @param {any} entity - The entity to convert
443
- * @param {ClassMetadata} classMetadata - the class metadata
444
- * @return {string} the content of the request
445
- */
385
+ function HttpError(message, baseResponse) {
386
+ var _this;
446
387
 
447
- }, {
448
- key: "serializeItem",
449
- value: function serializeItem(object, classMetadata) {
450
- var noralizedData = this.normalizeItem(object, classMetadata);
451
- return this.encodeItem(noralizedData, classMetadata);
452
- }
453
- /**
454
- * convert a plain object to an entity
455
- * @param {object} object - The plain javascript object
456
- * @param {ClassMetadata} classMetadata - the class metadata
457
- * @param {Record<string, unknown>} response - the HTTP response
458
- * @return {object} an entity
459
- */
388
+ _classCallCheck(this, HttpError);
460
389
 
461
- }, {
462
- key: "denormalizeItem",
463
- value: function denormalizeItem(object, classMetadata, response) {
464
- return object;
465
- }
466
- /**
467
- * convert a string containing an object to a plain javascript object
468
- * @param {string} rawData - The string fetched from the response
469
- * @param {ClassMetadata} classMetadata - the class metadata
470
- * @param {Record<string, unknown>} response - the HTTP response
471
- * @return {object} the normalized object
472
- */
390
+ _this = _super.call(this, message || 'Http errort'); // Set the prototype explicitly.
473
391
 
474
- }, {
475
- key: "decodeItem",
476
- value: function decodeItem(rawData, classMetadata, response) {
477
- throw new TypeError('`decodeItem` method must be implemented');
478
- }
479
- /**
480
- * convert a string containing an object to an entity
481
- * @param {string} rawData - The string fetched from the response
482
- * @param {ClassMetadata} classMetadata - the class metadata
483
- * @param {Record<string, unknown>} response - the HTTP response
484
- * @return {object} the entity
485
- */
392
+ _defineProperty(_assertThisInitialized(_this), "baseResponse", void 0);
486
393
 
487
- }, {
488
- key: "deserializeItem",
489
- value: function deserializeItem(rawData, classMetadata, response) {
490
- var object = this.decodeItem(rawData, classMetadata, response);
491
- return this.denormalizeItem(object, classMetadata, response);
492
- }
493
- /**
494
- * convert a plain object list to an entity list
495
- * @param {Iterable<object>} objectList - The plain javascript object list (or an iterable object)
496
- * @param {ClassMetadata} classMetadata - the class metadata
497
- * @param {Record<string, unknown>} response - the HTTP response
498
- * @return {Iterable<object>} a list of entities
499
- */
394
+ Object.setPrototypeOf(_assertThisInitialized(_this), OauthError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
500
395
 
501
- }, {
502
- key: "denormalizeList",
503
- value: function denormalizeList(objectList, classMetadata, response) {
504
- return objectList; // weird conversion as the declaration of list type is fuzzy
396
+ if (Error.captureStackTrace) {
397
+ Error.captureStackTrace(_assertThisInitialized(_this), OauthError);
505
398
  }
506
- /**
507
- * convert a string containing a list of objects to a list of plain javascript objects
508
- * @param {string} rawListData - The string fetched from the response
509
- * @param {ClassMetadata} classMetadata - the class metadata
510
- * @param {Record<string, unknown>} response - the HTTP response
511
- * @return {Iterable<object>} a list of normalized objects
512
- */
513
399
 
514
- }, {
515
- key: "decodeList",
516
- value: function decodeList(rawListData, classMetadata, response) {
517
- throw new TypeError('`deserializeList` method must be implemented');
518
- }
519
- /**
520
- * convert a string containing a list of objects to a list of entities
521
- * @param {string} rawListData - The string fetched from the response
522
- * @param {ClassMetadata} classMetadata - the class metadata
523
- * @param {Record<string, unknown>} response - the HTTP response
524
- * @return {Iterable<object>} a list of entities
525
- */
400
+ _this.name = 'HttpError';
401
+ _this.baseResponse = baseResponse;
402
+ return _this;
403
+ }
404
+ /**
405
+ * Get the JSON of the baseResponse directly, if possible
406
+ */
526
407
 
527
- }, {
528
- key: "deserializeList",
529
- value: function deserializeList(rawListData, classMetadata, response) {
530
- var objectList = this.decodeList(rawListData, classMetadata, response);
531
- return this.denormalizeList(objectList, classMetadata, response);
408
+
409
+ _createClass(HttpError, [{
410
+ key: "responseJson",
411
+ value: function responseJson() {
412
+ return this.baseResponse.json();
532
413
  }
533
414
  }]);
534
415
 
535
- return Serializer;
536
- }();
416
+ return HttpError;
417
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
537
418
 
538
- var JsSerializer = /*#__PURE__*/function (_Serializer) {
539
- _inherits(JsSerializer, _Serializer);
419
+ var OauthError = /*#__PURE__*/function (_Error2) {
420
+ _inherits(OauthError, _Error2);
540
421
 
541
- var _super = _createSuper(JsSerializer);
422
+ var _super2 = _createSuper(OauthError);
542
423
 
543
- function JsSerializer() {
544
- _classCallCheck(this, JsSerializer);
424
+ function OauthError(message, previousError) {
425
+ var _this2;
545
426
 
546
- return _super.apply(this, arguments);
547
- }
427
+ _classCallCheck(this, OauthError);
548
428
 
549
- _createClass(JsSerializer, [{
550
- key: "encodeItem",
551
- value: function encodeItem(object, classMetadata) {
552
- return JSON.stringify(object);
553
- }
554
- }, {
555
- key: "decodeItem",
556
- value: function decodeItem(rawData, classMetadata, response) {
557
- return JSON.parse(rawData);
558
- }
559
- }, {
560
- key: "decodeList",
561
- value: function decodeList(rawListData, classMetadata, response) {
562
- return JSON.parse(rawListData);
563
- }
564
- }]);
429
+ _this2 = _super2.call(this, message || 'Oauth error'); // Set the prototype explicitly.
565
430
 
566
- return JsSerializer;
567
- }(Serializer);
431
+ _defineProperty(_assertThisInitialized(_this2), "previousError", void 0);
568
432
 
569
- /* eslint-disable */
570
- // "fork" of https://github.com/facebook/immutable-js/blob/v4.0.0-rc.9/src/Predicates.js
571
- // because tree-shaking does not seems to work as expected
433
+ Object.setPrototypeOf(_assertThisInitialized(_this2), OauthError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
572
434
 
573
- /**
574
- * Copyright (c) 2014-present, Facebook, Inc.
575
- *
576
- * This source code is licensed under the MIT license found in the
577
- * LICENSE file in the root directory of this source tree.
578
- */
579
- var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
580
- var IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@';
581
- function isImmutable(maybeImmutable) {
582
- return isCollection(maybeImmutable) || isRecord(maybeImmutable);
583
- }
584
- function isCollection(maybeCollection) {
585
- return !!(maybeCollection && maybeCollection[IS_ITERABLE_SENTINEL]);
586
- }
587
- function isRecord(maybeRecord) {
588
- return !!(maybeRecord && maybeRecord[IS_RECORD_SENTINEL]);
589
- }
435
+ if (Error.captureStackTrace) {
436
+ Error.captureStackTrace(_assertThisInitialized(_this2), OauthError);
437
+ }
590
438
 
591
- /**
592
- * deep comparaison between objects
593
- */
594
- function objectDiffers(left, right) {
595
- var result = deepDiff.diff(left, right);
596
- return result ? result.length > 0 : false;
597
- }
598
- /**
599
- * get the id of an entity or return itself if string
600
- */
439
+ _this2.name = 'OauthError';
440
+ _this2.previousError = previousError;
441
+ return _this2;
442
+ }
601
443
 
444
+ return OauthError;
445
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
602
446
 
603
- function getEntityId(stringOrEntity, idSerializedKey) {
604
- if (_typeof(stringOrEntity) !== 'object') {
605
- return stringOrEntity;
606
- } // eslint-disable-next-line @typescript-eslint/ban-ts-comment
607
- // @ts-ignore
447
+ var InvalidGrantError = /*#__PURE__*/function (_OauthError) {
448
+ _inherits(InvalidGrantError, _OauthError);
608
449
 
450
+ var _super3 = _createSuper(InvalidGrantError);
609
451
 
610
- return stringOrEntity[idSerializedKey];
611
- }
612
- /**
613
- * find old relation value from the new relation id
614
- * if not found, returs the default serilazed model
615
- */
452
+ function InvalidGrantError(message, previousError) {
453
+ var _this3;
616
454
 
455
+ _classCallCheck(this, InvalidGrantError);
617
456
 
618
- function findOldRelation(newRelationValue, oldRelationValue, classMetadata) {
619
- var idSerializedKey = classMetadata.getIdentifierAttribute().serializedKey; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
620
- // @ts-ignore
621
-
622
- var relationValueId = getEntityId(newRelationValue, idSerializedKey);
623
- var foundValue = oldRelationValue && oldRelationValue.find(function (innerOldRelationValue) {
624
- var oldRelationValueId = getEntityId(innerOldRelationValue, idSerializedKey);
625
- return relationValueId === oldRelationValueId;
626
- });
627
-
628
- if (foundValue) {
629
- return foundValue;
630
- }
631
-
632
- return classMetadata.getDefaultSerializedModel();
633
- }
634
- /**
635
- * add all identifier from one to many relation list
636
- */
457
+ _this3 = _super3.call(this, message || 'Invalid grant error', previousError); // Set the prototype explicitly.
637
458
 
459
+ _defineProperty(_assertThisInitialized(_this3), "previousError", void 0);
638
460
 
639
- function getIdentifierForList(newValue, idSerializedKey) {
640
- return newValue.map(function (value) {
641
- if (Object.keys(value).includes(idSerializedKey)) {
642
- return _defineProperty({}, idSerializedKey, value[idSerializedKey]);
643
- }
461
+ Object.setPrototypeOf(_assertThisInitialized(_this3), InvalidGrantError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
644
462
 
645
- if (typeof value === 'string') {
646
- return value;
463
+ if (Error.captureStackTrace) {
464
+ Error.captureStackTrace(_assertThisInitialized(_this3), InvalidGrantError);
647
465
  }
648
466
 
649
- throw new TypeError('new value should include a list of string or objects containing the serialized key');
650
- });
651
- }
467
+ _this3.name = 'InvalidGrantError';
468
+ _this3.previousError = previousError;
469
+ return _this3;
470
+ }
652
471
 
653
- var _storage = new WeakMap();
472
+ return InvalidGrantError;
473
+ }(OauthError);
654
474
 
655
- var _enabled = new WeakMap();
475
+ var InvalidScopeError = /*#__PURE__*/function (_OauthError2) {
476
+ _inherits(InvalidScopeError, _OauthError2);
656
477
 
657
- var UnitOfWork = /*#__PURE__*/function () {
658
- function UnitOfWork(mapping) {
659
- var enabled = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
478
+ var _super4 = _createSuper(InvalidScopeError);
660
479
 
661
- _classCallCheck(this, UnitOfWork);
480
+ function InvalidScopeError(message, previousError) {
481
+ var _this4;
662
482
 
663
- _defineProperty(this, "mapping", void 0);
483
+ _classCallCheck(this, InvalidScopeError);
664
484
 
665
- _storage.set(this, {
666
- writable: true,
667
- value: void 0
668
- });
485
+ _this4 = _super4.call(this, message || 'Invalid scope error', previousError); // Set the prototype explicitly.
669
486
 
670
- _enabled.set(this, {
671
- writable: true,
672
- value: void 0
673
- });
487
+ _defineProperty(_assertThisInitialized(_this4), "previousError", void 0);
674
488
 
675
- this.mapping = mapping;
489
+ Object.setPrototypeOf(_assertThisInitialized(_this4), InvalidScopeError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
676
490
 
677
- _classPrivateFieldSet(this, _enabled, enabled);
491
+ if (Error.captureStackTrace) {
492
+ Error.captureStackTrace(_assertThisInitialized(_this4), InvalidScopeError);
493
+ }
678
494
 
679
- _classPrivateFieldSet(this, _storage, {});
495
+ _this4.name = 'InvalidScopeError';
496
+ _this4.previousError = previousError;
497
+ return _this4;
680
498
  }
681
499
 
682
- _createClass(UnitOfWork, [{
683
- key: "registerClean",
684
- value: function registerClean(id, entity) {
685
- if (!_classPrivateFieldGet(this, _enabled)) {
686
- return;
687
- }
500
+ return InvalidScopeError;
501
+ }(OauthError); // 400
688
502
 
689
- if (isImmutable(entity)) {
690
- _classPrivateFieldGet(this, _storage)[id] = entity;
691
- } else {
692
- _classPrivateFieldGet(this, _storage)[id] = _objectSpread2({}, entity);
693
- }
694
- }
695
- }, {
696
- key: "getDirtyEntity",
697
- value: function getDirtyEntity(id) {
698
- return _classPrivateFieldGet(this, _storage)[id];
699
- }
700
- }, {
701
- key: "clear",
702
- value: function clear(id) {
703
- delete _classPrivateFieldGet(this, _storage)[id];
704
- }
705
- }, {
706
- key: "getDirtyData",
707
- value: function getDirtyData(newSerializedModel, oldSerializedModel, classMetadata) {
708
- return this._getDirtyFields(newSerializedModel, oldSerializedModel, classMetadata);
709
- }
710
- }, {
711
- key: "_getDirtyFieldsForAttribute",
712
- value: function _getDirtyFieldsForAttribute(dirtyFieldsParam, key, attribute, oldValue, newValue) {
713
- var dirtyFields = dirtyFieldsParam;
714
503
 
715
- if (attribute.type === 'object') {
716
- if (oldValue === undefined || objectDiffers(oldValue, newValue)) {
717
- dirtyFields[key] = newValue;
718
- }
719
- } else if (oldValue !== newValue) {
720
- dirtyFields[key] = newValue;
721
- }
504
+ var BadRequestError = /*#__PURE__*/function (_HttpError) {
505
+ _inherits(BadRequestError, _HttpError);
722
506
 
723
- return dirtyFields;
724
- }
725
- }, {
726
- key: "_getDirtyFieldsForManyToOne",
727
- value: function _getDirtyFieldsForManyToOne(dirtyFieldsParam, key, oldValue, newValue, relationMetadata, idSerializedKey) {
728
- var dirtyFields = dirtyFieldsParam;
507
+ var _super5 = _createSuper(BadRequestError);
729
508
 
730
- if (oldValue !== newValue) {
731
- if (newValue === null) {
732
- dirtyFields[key] = null;
733
- return dirtyFields;
734
- }
509
+ function BadRequestError(message, baseResponse) {
510
+ var _this5;
735
511
 
736
- if (typeof oldValue === 'string' || typeof newValue === 'string') {
737
- dirtyFields[key] = newValue;
738
- }
512
+ _classCallCheck(this, BadRequestError);
739
513
 
740
- var recursiveDiff = this._getDirtyFields(newValue, oldValue, relationMetadata);
514
+ _this5 = _super5.call(this, message || 'Bad request', baseResponse); // Set the prototype explicitly.
741
515
 
742
- if (Object.keys(recursiveDiff).length > 0) {
743
- recursiveDiff[idSerializedKey] = getEntityId(newValue, idSerializedKey);
744
- dirtyFields[key] = recursiveDiff;
745
- }
746
- }
516
+ _defineProperty(_assertThisInitialized(_this5), "baseResponse", void 0);
747
517
 
748
- return dirtyFields;
518
+ Object.setPrototypeOf(_assertThisInitialized(_this5), BadRequestError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
519
+
520
+ if (Error.captureStackTrace) {
521
+ Error.captureStackTrace(_assertThisInitialized(_this5), BadRequestError);
749
522
  }
750
- }, {
751
- key: "_getDirtyFieldsForOneToMany",
752
- value: function _getDirtyFieldsForOneToMany(dirtyFieldsParam, key, idSerializedKey, relationMetadata, oldValue, newValue) {
753
- var _this = this;
754
523
 
755
- var dirtyFields = dirtyFieldsParam;
756
- var newValueLength = newValue ? newValue.length : 0;
757
- var oldValueLength = oldValue ? oldValue.length : 0; // number of items changed
524
+ _this5.name = 'BadRequestError';
525
+ _this5.baseResponse = baseResponse;
526
+ return _this5;
527
+ }
758
528
 
759
- if (newValueLength !== oldValueLength) {
760
- dirtyFields[key] = getIdentifierForList(newValue, idSerializedKey);
761
- }
529
+ return BadRequestError;
530
+ }(HttpError); // 401
762
531
 
763
- if (newValue && newValue.length > 0) {
764
- if (dirtyFields[key] === undefined) {
765
- dirtyFields[key] = [];
766
- }
767
532
 
768
- var relationList = newValue;
769
- relationList.forEach(function (newRelationValue, relationAttributeName) {
770
- var oldRelationValue = findOldRelation(newRelationValue, oldValue, relationMetadata);
533
+ var UnauthorizedError = /*#__PURE__*/function (_BadRequestError) {
534
+ _inherits(UnauthorizedError, _BadRequestError);
771
535
 
772
- if (newRelationValue !== oldRelationValue) {
773
- if (typeof newRelationValue === 'string' || typeof oldRelationValue === 'string') {
774
- dirtyFields[key][relationAttributeName] = newRelationValue;
775
- return;
776
- }
536
+ var _super6 = _createSuper(UnauthorizedError);
777
537
 
778
- var recursiveDiff = _this._getDirtyFields(newRelationValue, oldRelationValue, relationMetadata);
538
+ function UnauthorizedError(message, baseResponse) {
539
+ var _this6;
779
540
 
780
- if (Object.keys(recursiveDiff).length > 0) {
781
- var entityId = getEntityId(newRelationValue, idSerializedKey);
541
+ _classCallCheck(this, UnauthorizedError);
782
542
 
783
- if (entityId !== null) {
784
- recursiveDiff[idSerializedKey] = entityId;
785
- }
543
+ _this6 = _super6.call(this, message || 'Unauthorized', baseResponse); // Set the prototype explicitly.
786
544
 
787
- if (dirtyFields[key][relationAttributeName]) {
788
- Object.assign(dirtyFields[key][relationAttributeName], recursiveDiff);
789
- } else {
790
- dirtyFields[key][relationAttributeName] = recursiveDiff;
791
- }
792
- }
793
- }
794
- });
545
+ _defineProperty(_assertThisInitialized(_this6), "baseResponse", void 0);
795
546
 
796
- if (dirtyFields[key].length > 0) {
797
- // add identifier because one or more object linked has been updated
798
- // see test: 'get dirty data many to one update item'
799
- dirtyFields[key] = Object.assign(getIdentifierForList(newValue, idSerializedKey), dirtyFields[key]);
800
- } else {
801
- // no changes, no need to send the key with an empty array as value
802
- delete dirtyFields[key];
803
- }
804
- }
547
+ Object.setPrototypeOf(_assertThisInitialized(_this6), UnauthorizedError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
805
548
 
806
- return dirtyFields;
549
+ if (Error.captureStackTrace) {
550
+ Error.captureStackTrace(_assertThisInitialized(_this6), UnauthorizedError);
807
551
  }
808
- }, {
809
- key: "_getDirtyFields",
810
- value: function _getDirtyFields(newSerializedModel, oldSerializedModel, classMetadata) {
811
- var _this2 = this;
812
552
 
813
- var dirtyFields = {};
814
- Object.values(classMetadata.getAttributeList()).forEach(function (attribute) {
815
- var key = attribute.attributeName;
816
- var newValue = newSerializedModel[key];
817
- var oldValue = oldSerializedModel ? oldSerializedModel[key] : null;
818
- var currentRelation = classMetadata.getRelation(attribute.serializedKey);
553
+ _this6.name = 'UnauthorizedError';
554
+ _this6.baseResponse = baseResponse;
555
+ return _this6;
556
+ }
819
557
 
820
- if (newValue === undefined) {
821
- return;
822
- } // not a relation
558
+ return UnauthorizedError;
559
+ }(BadRequestError); // 403
823
560
 
824
561
 
825
- if (!currentRelation) {
826
- dirtyFields = _this2._getDirtyFieldsForAttribute(dirtyFields, key, attribute, oldValue, newValue);
827
- return;
828
- }
562
+ var ForbiddenError = /*#__PURE__*/function (_BadRequestError2) {
563
+ _inherits(ForbiddenError, _BadRequestError2);
829
564
 
830
- var relationMetadata = _this2.mapping.getClassMetadataByKey(currentRelation.targetMetadataKey);
565
+ var _super7 = _createSuper(ForbiddenError);
831
566
 
832
- if (!relationMetadata) {
833
- throw new TypeError("relation metadata is not set for relation ".concat(classMetadata.key, ".").concat(currentRelation.targetMetadataKey));
834
- }
567
+ function ForbiddenError(message, baseResponse) {
568
+ var _this7;
835
569
 
836
- var idSerializedKey = relationMetadata.getIdentifierAttribute().serializedKey; // MANY_TO_ONE relation
570
+ _classCallCheck(this, ForbiddenError);
837
571
 
838
- if (currentRelation.isRelationToOne()) {
839
- dirtyFields = _this2._getDirtyFieldsForManyToOne(dirtyFields, key, oldValue, newValue, relationMetadata, idSerializedKey);
840
- return;
841
- } // *_TO_MANY relation
572
+ _this7 = _super7.call(this, message || 'Forbidden', baseResponse); // Set the prototype explicitly.
842
573
 
574
+ _defineProperty(_assertThisInitialized(_this7), "baseResponse", void 0);
843
575
 
844
- dirtyFields = _this2._getDirtyFieldsForOneToMany(dirtyFields, key, idSerializedKey, relationMetadata, oldValue, newValue);
845
- });
846
- return dirtyFields;
576
+ Object.setPrototypeOf(_assertThisInitialized(_this7), ForbiddenError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
577
+
578
+ if (Error.captureStackTrace) {
579
+ Error.captureStackTrace(_assertThisInitialized(_this7), ForbiddenError);
847
580
  }
848
- }]);
849
581
 
850
- return UnitOfWork;
851
- }();
582
+ _this7.name = 'ForbiddenError';
583
+ _this7.baseResponse = baseResponse;
584
+ return _this7;
585
+ }
852
586
 
853
- var DEFAULT_CONFIG = {
587
+ return ForbiddenError;
588
+ }(BadRequestError); // 404
589
+
590
+
591
+ var ResourceNotFoundError = /*#__PURE__*/function (_BadRequestError3) {
592
+ _inherits(ResourceNotFoundError, _BadRequestError3);
593
+
594
+ var _super8 = _createSuper(ResourceNotFoundError);
595
+
596
+ function ResourceNotFoundError(message, baseResponse) {
597
+ var _this8;
598
+
599
+ _classCallCheck(this, ResourceNotFoundError);
600
+
601
+ _this8 = _super8.call(this, message || 'Resource is not found', baseResponse); // Set the prototype explicitly.
602
+
603
+ _defineProperty(_assertThisInitialized(_this8), "baseResponse", void 0);
604
+
605
+ Object.setPrototypeOf(_assertThisInitialized(_this8), ResourceNotFoundError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
606
+
607
+ if (Error.captureStackTrace) {
608
+ Error.captureStackTrace(_assertThisInitialized(_this8), ResourceNotFoundError);
609
+ }
610
+
611
+ _this8.name = 'ResourceNotFoundError';
612
+ _this8.baseResponse = baseResponse;
613
+ return _this8;
614
+ }
615
+
616
+ return ResourceNotFoundError;
617
+ }(BadRequestError); // 409
618
+
619
+
620
+ var ConflictError = /*#__PURE__*/function (_BadRequestError4) {
621
+ _inherits(ConflictError, _BadRequestError4);
622
+
623
+ var _super9 = _createSuper(ConflictError);
624
+
625
+ function ConflictError(message, baseResponse) {
626
+ var _this9;
627
+
628
+ _classCallCheck(this, ConflictError);
629
+
630
+ _this9 = _super9.call(this, message || 'Conflict detected', baseResponse); // Set the prototype explicitly.
631
+
632
+ _defineProperty(_assertThisInitialized(_this9), "baseResponse", void 0);
633
+
634
+ Object.setPrototypeOf(_assertThisInitialized(_this9), ConflictError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
635
+
636
+ if (Error.captureStackTrace) {
637
+ Error.captureStackTrace(_assertThisInitialized(_this9), ConflictError);
638
+ }
639
+
640
+ _this9.name = 'ConflictError';
641
+ _this9.baseResponse = baseResponse;
642
+ return _this9;
643
+ }
644
+
645
+ return ConflictError;
646
+ }(BadRequestError); // 500
647
+
648
+
649
+ var InternalServerError = /*#__PURE__*/function (_HttpError2) {
650
+ _inherits(InternalServerError, _HttpError2);
651
+
652
+ var _super10 = _createSuper(InternalServerError);
653
+
654
+ function InternalServerError(message, baseResponse) {
655
+ var _this10;
656
+
657
+ _classCallCheck(this, InternalServerError);
658
+
659
+ _this10 = _super10.call(this, message || 'Internal server error', baseResponse); // Set the prototype explicitly.
660
+
661
+ _defineProperty(_assertThisInitialized(_this10), "baseResponse", void 0);
662
+
663
+ Object.setPrototypeOf(_assertThisInitialized(_this10), InternalServerError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
664
+
665
+ if (Error.captureStackTrace) {
666
+ Error.captureStackTrace(_assertThisInitialized(_this10), InternalServerError);
667
+ }
668
+
669
+ _this10.name = 'InternalServerError';
670
+ _this10.baseResponse = baseResponse;
671
+ return _this10;
672
+ }
673
+
674
+ return InternalServerError;
675
+ }(HttpError);
676
+ /**
677
+ * @returns {HttpError}
678
+ */
679
+
680
+
681
+ function getHttpErrorFromResponse(originalResponse) {
682
+ var response = originalResponse.clone();
683
+
684
+ switch (true) {
685
+ case response.status === 401:
686
+ return new UnauthorizedError(null, response);
687
+
688
+ case response.status === 403:
689
+ return new ForbiddenError(null, response);
690
+
691
+ case response.status === 404:
692
+ return new ResourceNotFoundError(null, response);
693
+
694
+ case response.status === 409:
695
+ return new ConflictError(null, response);
696
+
697
+ case response.status >= 400 && response.status < 500:
698
+ return new BadRequestError(null, response);
699
+
700
+ case response.status >= 500 && response.status < 600:
701
+ return new InternalServerError(null, response);
702
+
703
+ default:
704
+ return new HttpError(null, response);
705
+ }
706
+ }
707
+
708
+ function isOauthError(body) {
709
+ var _ref;
710
+
711
+ return typeof ((_ref = body) === null || _ref === void 0 ? void 0 : _ref.error) === 'string';
712
+ }
713
+
714
+ var DEFAULT_CONFIG = {
854
715
  collectionKey: 'hydra:member'
855
716
  };
856
717
 
@@ -985,6 +846,38 @@
985
846
  return Mapping;
986
847
  }();
987
848
 
849
+ var Attribute =
850
+ /**
851
+ * @param {string} serializedKey the key returned from your API
852
+ * @param {null|string} attributeName the name in your entity, default to the `serializedKey` attribute
853
+ * @param {string} type type of the attribute
854
+ * @param {boolean} isIdentifier is this attribute the entity identifier
855
+ */
856
+ function Attribute(serializedKey) {
857
+ var attributeName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
858
+ var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'string';
859
+ var isIdentifier = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
860
+
861
+ _classCallCheck(this, Attribute);
862
+
863
+ _defineProperty(this, "serializedKey", void 0);
864
+
865
+ _defineProperty(this, "attributeName", void 0);
866
+
867
+ _defineProperty(this, "type", void 0);
868
+
869
+ _defineProperty(this, "isIdentifier", void 0);
870
+
871
+ if (!serializedKey) {
872
+ throw new TypeError('`serializedKey` must not be empty');
873
+ }
874
+
875
+ this.serializedKey = serializedKey;
876
+ this.attributeName = attributeName || this.serializedKey;
877
+ this.type = type;
878
+ this.isIdentifier = isIdentifier;
879
+ };
880
+
988
881
  /* eslint-disable import/prefer-default-export */
989
882
  // eslint-disable-next-line import/no-duplicates
990
883
  // eslint-disable-next-line import/no-duplicates
@@ -994,1266 +887,1422 @@
994
887
  return new metadata.repositoryClass(sdk, metadata, isUnitOfWorkEnabled);
995
888
  }
996
889
 
997
- var _repositoryList = new WeakMap();
890
+ /* eslint-disable consistent-return */
891
+ function removeAuthorization(headers) {
892
+ if (!headers) {
893
+ return;
894
+ }
998
895
 
999
- var RestClientSdk = /*#__PURE__*/function () {
1000
- function RestClientSdk(tokenStorage, config, mapping) {
1001
- var serializer = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new JsSerializer();
896
+ if (headers instanceof Headers) {
897
+ headers["delete"]('Authorization');
898
+ return headers;
899
+ }
1002
900
 
1003
- _classCallCheck(this, RestClientSdk);
901
+ var filterAuthorization = function filterAuthorization(entries) {
902
+ return entries.filter(function (header) {
903
+ return header[0] !== 'Authorization';
904
+ });
905
+ };
1004
906
 
1005
- _defineProperty(this, "config", void 0);
907
+ if (Array.isArray(headers)) {
908
+ return filterAuthorization(headers);
909
+ }
1006
910
 
1007
- _defineProperty(this, "tokenStorage", void 0);
911
+ return Object.fromEntries(filterAuthorization(Object.entries(headers)));
912
+ }
913
+ /**
914
+ * remove undefined key, usefull to remove Content-Type for example.
915
+ * Does not apply on "Headers" instance as values are string in there.
916
+ */
1008
917
 
1009
- _defineProperty(this, "serializer", void 0);
918
+ function removeUndefinedHeaders(headers) {
919
+ if (headers instanceof Headers) {
920
+ return headers;
921
+ }
1010
922
 
1011
- _defineProperty(this, "mapping", void 0);
923
+ var filterEntries = function filterEntries(entries) {
924
+ return entries.filter(function (header) {
925
+ return header[1] !== undefined;
926
+ });
927
+ };
1012
928
 
1013
- _defineProperty(this, "unitOfWork", void 0);
929
+ if (Array.isArray(headers)) {
930
+ return filterEntries(headers);
931
+ }
1014
932
 
1015
- _repositoryList.set(this, {
1016
- writable: true,
1017
- value: void 0
1018
- });
933
+ return Object.fromEntries(filterEntries(Object.entries(headers)));
934
+ }
935
+ function convertToRecord(headers) {
936
+ if (headers instanceof Headers) {
937
+ return Object.fromEntries(headers.entries());
938
+ }
1019
939
 
1020
- this.checkConfigValidity(config);
940
+ if (Array.isArray(headers)) {
941
+ return Object.fromEntries(headers);
942
+ }
1021
943
 
1022
- if (!(mapping instanceof Mapping)) {
1023
- throw new TypeError('mapping should be an instance of `Mapping`');
1024
- }
944
+ return headers;
945
+ }
1025
946
 
1026
- this.config = this._mergeWithBaseConfig(config);
1027
- this.tokenStorage = tokenStorage;
1028
- this.serializer = serializer;
1029
- this.mapping = mapping;
1030
- this.unitOfWork = new UnitOfWork(this.mapping, this.config.unitOfWorkEnabled);
947
+ var EXPIRE_LIMIT_SECONDS = 300; // = 5 minutes
1031
948
 
1032
- _classPrivateFieldSet(this, _repositoryList, {});
1033
- }
1034
- /**
1035
- * get a repository by it's metadata "key" attribute
1036
- *
1037
- * @param {string} key the repository "key" (the first argument of `new ClassMetadata`)
1038
- */
949
+ var _tokenStorage = new WeakMap();
1039
950
 
951
+ var _isUnitOfWorkEnabled = new WeakMap();
1040
952
 
1041
- _createClass(RestClientSdk, [{
1042
- key: "getRepository",
1043
- value: function getRepository(key) {
1044
- if (!_classPrivateFieldGet(this, _repositoryList)[key]) {
1045
- var metadata = this.mapping.getClassMetadataByKey(key);
953
+ var AbstractClient = /*#__PURE__*/function () {
954
+ function AbstractClient(sdk, metadata) {
955
+ var isUnitOfWorkEnabled = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
1046
956
 
1047
- if (!metadata) {
1048
- throw new Error("Unable to get metadata for repository ".concat(key));
1049
- } // eslint-disable-next-line new-cap
957
+ _classCallCheck(this, AbstractClient);
1050
958
 
959
+ _defineProperty(this, "sdk", void 0);
1051
960
 
1052
- _classPrivateFieldGet(this, _repositoryList)[key] = generateRepository(this, metadata);
1053
- } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
961
+ _tokenStorage.set(this, {
962
+ writable: true,
963
+ value: void 0
964
+ });
1054
965
 
966
+ _defineProperty(this, "serializer", void 0);
1055
967
 
1056
- return _classPrivateFieldGet(this, _repositoryList)[key];
1057
- }
1058
- }, {
1059
- key: "_mergeWithBaseConfig",
1060
- value: function _mergeWithBaseConfig(config) {
1061
- var newConfig = config;
1062
- newConfig.useDefaultParameters = config.useDefaultParameters === undefined ? true : config.useDefaultParameters;
1063
- newConfig.authorizationType = config.authorizationType || 'Bearer';
1064
- return newConfig;
1065
- }
1066
- }, {
1067
- key: "checkConfigValidity",
1068
- value: function checkConfigValidity(config) {
1069
- if (!(config && config.path && config.scheme)) {
1070
- throw new RangeError("SDK config is not valid, it should contain a \"path\", a \"scheme\" parameter,\n and may contain a \"port\" and a \"useDefaultParameters\" parameter");
1071
- }
1072
- }
1073
- }]);
1074
-
1075
- return RestClientSdk;
1076
- }();
1077
-
1078
- /* eslint-disable max-classes-per-file, no-use-before-define */
1079
-
1080
- /**
1081
- * It's a bit tricky to extends native errors
1082
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
1083
- */
1084
- var HttpError = /*#__PURE__*/function (_Error) {
1085
- _inherits(HttpError, _Error);
1086
-
1087
- var _super = _createSuper(HttpError);
1088
-
1089
- function HttpError(message, baseResponse) {
1090
- var _this;
1091
-
1092
- _classCallCheck(this, HttpError);
968
+ _defineProperty(this, "metadata", void 0);
1093
969
 
1094
- _this = _super.call(this, message || 'Http errort'); // Set the prototype explicitly.
970
+ _isUnitOfWorkEnabled.set(this, {
971
+ writable: true,
972
+ value: void 0
973
+ });
1095
974
 
1096
- _defineProperty(_assertThisInitialized(_this), "baseResponse", void 0);
975
+ this.sdk = sdk;
1097
976
 
1098
- Object.setPrototypeOf(_assertThisInitialized(_this), OauthError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
977
+ _classPrivateFieldSet(this, _tokenStorage, sdk.tokenStorage);
1099
978
 
1100
- if (Error.captureStackTrace) {
1101
- Error.captureStackTrace(_assertThisInitialized(_this), OauthError);
1102
- }
979
+ this.serializer = sdk.serializer;
980
+ this.metadata = metadata;
1103
981
 
1104
- _this.name = 'HttpError';
1105
- _this.baseResponse = baseResponse;
1106
- return _this;
982
+ _classPrivateFieldSet(this, _isUnitOfWorkEnabled, isUnitOfWorkEnabled);
1107
983
  }
1108
- /**
1109
- * Get the JSON of the baseResponse directly, if possible
1110
- */
1111
984
 
985
+ _createClass(AbstractClient, [{
986
+ key: "withUnitOfWork",
987
+ value: function withUnitOfWork(enabled) {
988
+ // eslint-disable-next-line new-cap
989
+ return generateRepository(this.sdk, this.metadata, enabled);
990
+ }
991
+ }, {
992
+ key: "getDefaultParameters",
993
+ value: function getDefaultParameters() {
994
+ return {};
995
+ } // eslint-disable-next-line @typescript-eslint/no-unused-vars
1112
996
 
1113
- _createClass(HttpError, [{
1114
- key: "responseJson",
1115
- value: function () {
1116
- var _responseJson = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
1117
- return regeneratorRuntime.wrap(function _callee$(_context) {
1118
- while (1) {
1119
- switch (_context.prev = _context.next) {
1120
- case 0:
1121
- return _context.abrupt("return", this.baseResponse.json());
1122
-
1123
- case 1:
1124
- case "end":
1125
- return _context.stop();
1126
- }
1127
- }
1128
- }, _callee, this);
1129
- }));
997
+ }, {
998
+ key: "getPathBase",
999
+ value: function getPathBase(pathParameters) {
1000
+ return "/".concat(this.metadata.pathRoot);
1001
+ }
1002
+ }, {
1003
+ key: "getEntityURI",
1004
+ value: function getEntityURI(entity) {
1005
+ var idValue = this._getEntityIdentifier(entity);
1130
1006
 
1131
- function responseJson() {
1132
- return _responseJson.apply(this, arguments);
1007
+ if (idValue === null) {
1008
+ throw new Error('Cannot call `getEntityURI for entity without id.`');
1133
1009
  }
1134
1010
 
1135
- return responseJson;
1136
- }()
1137
- }]);
1011
+ if (typeof idValue === 'number') {
1012
+ if (Number.isFinite(idValue)) {
1013
+ idValue = idValue.toString();
1014
+ } else {
1015
+ throw new Error('Unable to handle non-finite number');
1016
+ }
1017
+ }
1138
1018
 
1139
- return HttpError;
1140
- }( /*#__PURE__*/_wrapNativeSuper(Error));
1019
+ var pathBase = this.getPathBase({});
1141
1020
 
1142
- var OauthError = /*#__PURE__*/function (_Error2) {
1143
- _inherits(OauthError, _Error2);
1021
+ if (idValue.indexOf(pathBase) > -1) {
1022
+ return idValue;
1023
+ }
1144
1024
 
1145
- var _super2 = _createSuper(OauthError);
1025
+ return "".concat(pathBase, "/").concat(idValue);
1026
+ }
1027
+ /**
1028
+ * get an entity by its id
1029
+ *
1030
+ * @param {string|number} id the entity identifier
1031
+ * @param {Record<string, unknown>} queryParam query parameters that will be added to the request
1032
+ * @param {Record<string, unknown>} pathParameters path parameters, will be pass to the `getPathBase` method
1033
+ * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1034
+ */
1146
1035
 
1147
- function OauthError(message, previousError) {
1148
- var _this2;
1036
+ }, {
1037
+ key: "find",
1038
+ value: function find(id) {
1039
+ var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1040
+ var pathParameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1041
+ var requestParams = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1149
1042
 
1150
- _classCallCheck(this, OauthError);
1043
+ var url = this._generateUrlFromParams(queryParam, pathParameters, id);
1151
1044
 
1152
- _this2 = _super2.call(this, message || 'Oauth error'); // Set the prototype explicitly.
1045
+ return this.deserializeResponse(this.authorizedFetch(url, requestParams), 'item');
1046
+ }
1047
+ /**
1048
+ * get a list of entities by some parameters
1049
+ *
1050
+ * @param {Record<string, unknown>} queryParam query parameters that will be added to the request
1051
+ * @param {Record<string, unknown>} pathParameters path parameters, will be pass to the `getPathBase` method
1052
+ * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1053
+ */
1153
1054
 
1154
- _defineProperty(_assertThisInitialized(_this2), "previousError", void 0);
1055
+ }, {
1056
+ key: "findBy",
1057
+ value: function findBy(queryParam) {
1058
+ var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1059
+ var requestParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1155
1060
 
1156
- Object.setPrototypeOf(_assertThisInitialized(_this2), OauthError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
1061
+ var url = this._generateUrlFromParams(queryParam, pathParameters);
1157
1062
 
1158
- if (Error.captureStackTrace) {
1159
- Error.captureStackTrace(_assertThisInitialized(_this2), OauthError);
1063
+ return this.deserializeResponse(this.authorizedFetch(url, requestParams), 'list');
1160
1064
  }
1065
+ /**
1066
+ * get a list of all entities
1067
+ *
1068
+ * @param {Record<string, unknown>} queryParam query parameters that will be added to the request
1069
+ * @param {Record<string, unknown>} pathParameters path parameters, will be pass to the `getPathBase` method
1070
+ * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1071
+ */
1161
1072
 
1162
- _this2.name = 'OauthError';
1163
- _this2.previousError = previousError;
1164
- return _this2;
1165
- }
1073
+ }, {
1074
+ key: "findAll",
1075
+ value: function findAll() {
1076
+ var queryParam = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1077
+ var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1078
+ var requestParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1079
+ return this.findBy(queryParam, pathParameters, requestParams);
1080
+ }
1081
+ /**
1082
+ * create an entity
1083
+ *
1084
+ * @param {Record<string, unknown>} entity the entity to persist
1085
+ * @param {Record<string, unknown>} queryParam query parameters that will be added to the request
1086
+ * @param {Record<string, unknown>} pathParameters path parameters, will be pass to the `getPathBase` method
1087
+ * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1088
+ */
1166
1089
 
1167
- return OauthError;
1168
- }( /*#__PURE__*/_wrapNativeSuper(Error));
1090
+ }, {
1091
+ key: "create",
1092
+ value: function create(entity) {
1093
+ var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1094
+ var pathParameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1095
+ var requestParams = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1169
1096
 
1170
- var InvalidGrantError = /*#__PURE__*/function (_OauthError) {
1171
- _inherits(InvalidGrantError, _OauthError);
1097
+ this._throwIfUnitOfWorkIsDisabled();
1172
1098
 
1173
- var _super3 = _createSuper(InvalidGrantError);
1099
+ var url = new URI(this.getPathBase(pathParameters));
1100
+ url.addSearch(queryParam);
1101
+ var oldSerializedModel = this.metadata.getDefaultSerializedModel();
1102
+ var newSerializedModel = this.serializer.normalizeItem(entity, this.metadata);
1103
+ var diff = this.sdk.unitOfWork.getDirtyData(newSerializedModel, oldSerializedModel, this.metadata);
1104
+ return this.deserializeResponse(this.authorizedFetch(url, _objectSpread2({
1105
+ method: 'POST',
1106
+ body: this.serializer.encodeItem(diff, this.metadata)
1107
+ }, requestParams)), 'item');
1108
+ }
1109
+ /**
1110
+ * update an entity
1111
+ *
1112
+ * @param {Record<string, unknown>} entity the entity to update
1113
+ * @param {Record<string, unknown>} queryParam query parameters that will be added to the request
1114
+ * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1115
+ */
1174
1116
 
1175
- function InvalidGrantError(message, previousError) {
1176
- var _this3;
1117
+ }, {
1118
+ key: "update",
1119
+ value: function update(entity) {
1120
+ var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1121
+ var requestParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1177
1122
 
1178
- _classCallCheck(this, InvalidGrantError);
1123
+ this._throwIfUnitOfWorkIsDisabled();
1179
1124
 
1180
- _this3 = _super3.call(this, message || 'Invalid grant error', previousError); // Set the prototype explicitly.
1125
+ var url = new URI(this.getEntityURI(entity));
1126
+ url.addSearch(queryParam);
1127
+ var newSerializedModel = this.serializer.normalizeItem(entity, this.metadata);
1181
1128
 
1182
- _defineProperty(_assertThisInitialized(_this3), "previousError", void 0);
1129
+ var identifier = this._getEntityIdentifier(newSerializedModel);
1183
1130
 
1184
- Object.setPrototypeOf(_assertThisInitialized(_this3), InvalidGrantError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
1131
+ var oldModel;
1185
1132
 
1186
- if (Error.captureStackTrace) {
1187
- Error.captureStackTrace(_assertThisInitialized(_this3), InvalidGrantError);
1188
- }
1133
+ if (identifier !== null) {
1134
+ oldModel = this.sdk.unitOfWork.getDirtyEntity(identifier);
1135
+ }
1189
1136
 
1190
- _this3.name = 'InvalidGrantError';
1191
- _this3.previousError = previousError;
1192
- return _this3;
1193
- }
1137
+ if (oldModel) {
1138
+ newSerializedModel = this.sdk.unitOfWork.getDirtyData(newSerializedModel, oldModel, this.metadata);
1139
+ }
1194
1140
 
1195
- return InvalidGrantError;
1196
- }(OauthError);
1141
+ return this.deserializeResponse(this.authorizedFetch(url, _objectSpread2({
1142
+ method: 'PUT',
1143
+ body: this.serializer.encodeItem(newSerializedModel, this.metadata)
1144
+ }, requestParams)), 'item');
1145
+ }
1146
+ /**
1147
+ * delete an entity
1148
+ *
1149
+ * @param {Record<string, unknown>} the entity to delete
1150
+ * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1151
+ */
1197
1152
 
1198
- var InvalidScopeError = /*#__PURE__*/function (_OauthError2) {
1199
- _inherits(InvalidScopeError, _OauthError2);
1153
+ }, {
1154
+ key: "delete",
1155
+ value: function _delete(entity) {
1156
+ var _this = this;
1200
1157
 
1201
- var _super4 = _createSuper(InvalidScopeError);
1158
+ var requestParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1202
1159
 
1203
- function InvalidScopeError(message, previousError) {
1204
- var _this4;
1160
+ this._throwIfUnitOfWorkIsDisabled();
1205
1161
 
1206
- _classCallCheck(this, InvalidScopeError);
1162
+ var url = this.getEntityURI(entity);
1207
1163
 
1208
- _this4 = _super4.call(this, message || 'Invalid scope error', previousError); // Set the prototype explicitly.
1164
+ var identifier = this._getEntityIdentifier(entity);
1209
1165
 
1210
- _defineProperty(_assertThisInitialized(_this4), "previousError", void 0);
1211
-
1212
- Object.setPrototypeOf(_assertThisInitialized(_this4), InvalidScopeError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
1166
+ return this.authorizedFetch(url, _objectSpread2({
1167
+ method: 'DELETE'
1168
+ }, requestParams)).then(function (response) {
1169
+ if (identifier !== null) {
1170
+ _this.sdk.unitOfWork.clear(identifier);
1171
+ }
1213
1172
 
1214
- if (Error.captureStackTrace) {
1215
- Error.captureStackTrace(_assertThisInitialized(_this4), InvalidScopeError);
1173
+ return response;
1174
+ });
1216
1175
  }
1176
+ }, {
1177
+ key: "deserializeResponse",
1178
+ value: function deserializeResponse(requestPromise, listOrItem) {
1179
+ var _this2 = this;
1217
1180
 
1218
- _this4.name = 'InvalidScopeError';
1219
- _this4.previousError = previousError;
1220
- return _this4;
1221
- }
1222
-
1223
- return InvalidScopeError;
1224
- }(OauthError); // 400
1181
+ return requestPromise.then(function (response) {
1182
+ return response.text().then(function (text) {
1183
+ return {
1184
+ response: response,
1185
+ text: text
1186
+ };
1187
+ });
1188
+ }).then(function (_ref) {
1189
+ var response = _ref.response,
1190
+ text = _ref.text;
1225
1191
 
1192
+ if (listOrItem === 'list') {
1193
+ // for list, we need to deserialize the result to get an object
1194
+ var itemList = _this2.serializer.deserializeList(text, _this2.metadata, response);
1226
1195
 
1227
- var BadRequestError = /*#__PURE__*/function (_HttpError) {
1228
- _inherits(BadRequestError, _HttpError);
1196
+ if (_classPrivateFieldGet(_this2, _isUnitOfWorkEnabled)) {
1197
+ // eslint-disable-next-line no-restricted-syntax
1198
+ var _iterator = _createForOfIteratorHelper(itemList),
1199
+ _step;
1229
1200
 
1230
- var _super5 = _createSuper(BadRequestError);
1201
+ try {
1202
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
1203
+ var _decodedItem = _step.value;
1231
1204
 
1232
- function BadRequestError(message, baseResponse) {
1233
- var _this5;
1205
+ var _identifier = _this2._getEntityIdentifier(_decodedItem);
1234
1206
 
1235
- _classCallCheck(this, BadRequestError);
1207
+ var normalizedItem = _this2.serializer.normalizeItem(_decodedItem, _this2.metadata); // then we register the re-normalized item
1236
1208
 
1237
- _this5 = _super5.call(this, message || 'Bad request', baseResponse); // Set the prototype explicitly.
1238
1209
 
1239
- _defineProperty(_assertThisInitialized(_this5), "baseResponse", void 0);
1210
+ if (_identifier !== null) {
1211
+ _this2.sdk.unitOfWork.registerClean(_identifier, normalizedItem);
1212
+ }
1213
+ }
1214
+ } catch (err) {
1215
+ _iterator.e(err);
1216
+ } finally {
1217
+ _iterator.f();
1218
+ }
1219
+ }
1240
1220
 
1241
- Object.setPrototypeOf(_assertThisInitialized(_this5), BadRequestError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
1221
+ return itemList;
1222
+ } // for items, we can just decode the item (ie. transform it to JS object)
1242
1223
 
1243
- if (Error.captureStackTrace) {
1244
- Error.captureStackTrace(_assertThisInitialized(_this5), BadRequestError);
1245
- }
1246
1224
 
1247
- _this5.name = 'BadRequestError';
1248
- _this5.baseResponse = baseResponse;
1249
- return _this5;
1250
- }
1225
+ var decodedItem = _this2.serializer.decodeItem(text, _this2.metadata, response); // and register it directy without deserializing + renormalizing
1251
1226
 
1252
- return BadRequestError;
1253
- }(HttpError); // 401
1254
1227
 
1228
+ var identifier = _this2._getEntityIdentifier(decodedItem); // and finally return the denormalized item
1255
1229
 
1256
- var UnauthorizedError = /*#__PURE__*/function (_BadRequestError) {
1257
- _inherits(UnauthorizedError, _BadRequestError);
1258
1230
 
1259
- var _super6 = _createSuper(UnauthorizedError);
1231
+ var item = _this2.serializer.denormalizeItem(decodedItem, _this2.metadata, response);
1260
1232
 
1261
- function UnauthorizedError(message, baseResponse) {
1262
- var _this6;
1233
+ if (_classPrivateFieldGet(_this2, _isUnitOfWorkEnabled) && identifier !== null) {
1234
+ _this2.sdk.unitOfWork.registerClean(identifier, _this2.serializer.normalizeItem(item, _this2.metadata));
1235
+ }
1263
1236
 
1264
- _classCallCheck(this, UnauthorizedError);
1237
+ return item;
1238
+ });
1239
+ }
1240
+ }, {
1241
+ key: "makeUri",
1242
+ value: function makeUri(input) {
1243
+ var url = input instanceof URI ? input : new URI(input);
1244
+ url.host(this.sdk.config.path).scheme(this.sdk.config.scheme);
1265
1245
 
1266
- _this6 = _super6.call(this, message || 'Unauthorized', baseResponse); // Set the prototype explicitly.
1246
+ if (this.sdk.config.port) {
1247
+ url.port(String(this.sdk.config.port));
1248
+ }
1267
1249
 
1268
- _defineProperty(_assertThisInitialized(_this6), "baseResponse", void 0);
1250
+ if (this.sdk.mapping.idPrefix) {
1251
+ var segments = url.segment();
1269
1252
 
1270
- Object.setPrototypeOf(_assertThisInitialized(_this6), UnauthorizedError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
1253
+ if (!url.pathname().startsWith(this.sdk.mapping.idPrefix)) {
1254
+ segments.unshift(this.sdk.mapping.idPrefix);
1255
+ url.segment(segments);
1256
+ }
1257
+ }
1271
1258
 
1272
- if (Error.captureStackTrace) {
1273
- Error.captureStackTrace(_assertThisInitialized(_this6), UnauthorizedError);
1259
+ return url;
1260
+ }
1261
+ }, {
1262
+ key: "authorizedFetch",
1263
+ value: function authorizedFetch(input) {
1264
+ var requestParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1265
+ var url = this.makeUri(input);
1266
+ return this._fetchWithToken(url.toString(), requestParams);
1274
1267
  }
1268
+ }, {
1269
+ key: "_generateUrlFromParams",
1270
+ value: function _generateUrlFromParams(queryParam) {
1271
+ var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1272
+ var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
1273
+ var params = queryParam;
1275
1274
 
1276
- _this6.name = 'UnauthorizedError';
1277
- _this6.baseResponse = baseResponse;
1278
- return _this6;
1279
- }
1275
+ if (this.sdk.config.useDefaultParameters) {
1276
+ Object.assign(params, this.getDefaultParameters());
1277
+ }
1280
1278
 
1281
- return UnauthorizedError;
1282
- }(BadRequestError); // 403
1279
+ var pathBase = this.getPathBase(pathParameters);
1280
+ var url = null;
1283
1281
 
1282
+ if (id) {
1283
+ var testPathBase = this.sdk.mapping.idPrefix ? "".concat(this.sdk.mapping.idPrefix).concat(pathBase) : pathBase;
1284
1284
 
1285
- var ForbiddenError = /*#__PURE__*/function (_BadRequestError2) {
1286
- _inherits(ForbiddenError, _BadRequestError2);
1285
+ if (typeof id === 'string' && id.startsWith(testPathBase)) {
1286
+ url = new URI(id);
1287
+ } else {
1288
+ url = new URI("".concat(pathBase, "/").concat(id));
1289
+ }
1290
+ } else {
1291
+ url = new URI(pathBase);
1292
+ }
1287
1293
 
1288
- var _super7 = _createSuper(ForbiddenError);
1294
+ if (params) {
1295
+ url.addSearch(params);
1296
+ }
1289
1297
 
1290
- function ForbiddenError(message, baseResponse) {
1291
- var _this7;
1298
+ return url;
1299
+ }
1300
+ }, {
1301
+ key: "_fetchWithToken",
1302
+ value: function _fetchWithToken(input) {
1303
+ var _this3 = this;
1292
1304
 
1293
- _classCallCheck(this, ForbiddenError);
1305
+ var requestParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1294
1306
 
1295
- _this7 = _super7.call(this, message || 'Forbidden', baseResponse); // Set the prototype explicitly.
1307
+ if (!input) {
1308
+ throw new Error('input is empty');
1309
+ }
1296
1310
 
1297
- _defineProperty(_assertThisInitialized(_this7), "baseResponse", void 0);
1311
+ if (_classPrivateFieldGet(this, _tokenStorage)) {
1312
+ return _classPrivateFieldGet(this, _tokenStorage).getCurrentTokenExpiresIn().then(function (accessTokenExpiresIn) {
1313
+ if (accessTokenExpiresIn !== null && accessTokenExpiresIn <= EXPIRE_LIMIT_SECONDS) {
1314
+ return _classPrivateFieldGet(_this3, _tokenStorage).refreshToken().then(function (refreshedTokenObject) {
1315
+ return refreshedTokenObject.access_token;
1316
+ });
1317
+ }
1298
1318
 
1299
- Object.setPrototypeOf(_assertThisInitialized(_this7), ForbiddenError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
1319
+ return _classPrivateFieldGet(_this3, _tokenStorage).getAccessToken();
1320
+ }).then(function (token) {
1321
+ return _this3._doFetch(token, input, requestParams);
1322
+ });
1323
+ }
1300
1324
 
1301
- if (Error.captureStackTrace) {
1302
- Error.captureStackTrace(_assertThisInitialized(_this7), ForbiddenError);
1325
+ return this._doFetch(null, input, requestParams);
1303
1326
  }
1327
+ }, {
1328
+ key: "_refreshTokenAndRefetch",
1329
+ value: function _refreshTokenAndRefetch(input) {
1330
+ var _this4 = this;
1304
1331
 
1305
- _this7.name = 'ForbiddenError';
1306
- _this7.baseResponse = baseResponse;
1307
- return _this7;
1308
- }
1309
-
1310
- return ForbiddenError;
1311
- }(BadRequestError); // 404
1332
+ var requestParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1333
+ return _classPrivateFieldGet(this, _tokenStorage).refreshToken().then(function () {
1334
+ // eslint-disable-next-line prefer-const
1335
+ var headers = requestParams.headers,
1336
+ rest = _objectWithoutProperties(requestParams, ["headers"]);
1312
1337
 
1338
+ var updatedRequestParams = _objectSpread2(_objectSpread2({}, rest), {}, {
1339
+ headers: removeAuthorization(headers)
1340
+ });
1313
1341
 
1314
- var ResourceNotFoundError = /*#__PURE__*/function (_BadRequestError3) {
1315
- _inherits(ResourceNotFoundError, _BadRequestError3);
1342
+ return _this4._fetchWithToken(input, updatedRequestParams);
1343
+ });
1344
+ }
1345
+ }, {
1346
+ key: "_manageUnauthorized",
1347
+ value: function _manageUnauthorized(response, input) {
1348
+ var _this5 = this;
1316
1349
 
1317
- var _super8 = _createSuper(ResourceNotFoundError);
1350
+ var requestParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1351
+ var error = getHttpErrorFromResponse(response); // https://tools.ietf.org/html/rfc2617#section-1.2
1318
1352
 
1319
- function ResourceNotFoundError(message, baseResponse) {
1320
- var _this8;
1353
+ var authorizationHeader = response.headers.get('www-authenticate');
1321
1354
 
1322
- _classCallCheck(this, ResourceNotFoundError);
1355
+ if (authorizationHeader) {
1356
+ var invalidGrant = authorizationHeader.indexOf('error="invalid_grant"') > -1;
1323
1357
 
1324
- _this8 = _super8.call(this, message || 'Resource is not found', baseResponse); // Set the prototype explicitly.
1358
+ if (invalidGrant && _classPrivateFieldGet(this, _tokenStorage)) {
1359
+ return this._refreshTokenAndRefetch(input, requestParams);
1360
+ }
1325
1361
 
1326
- _defineProperty(_assertThisInitialized(_this8), "baseResponse", void 0);
1362
+ throw error;
1363
+ } else {
1364
+ // if www-authenticate header is missing, try and read json response
1365
+ return response.json().then(function (body) {
1366
+ if (_classPrivateFieldGet(_this5, _tokenStorage) && body.error === 'invalid_grant') {
1367
+ return _this5._refreshTokenAndRefetch(input, requestParams);
1368
+ }
1327
1369
 
1328
- Object.setPrototypeOf(_assertThisInitialized(_this8), ResourceNotFoundError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
1370
+ throw error;
1371
+ })["catch"](function (err) {
1372
+ if (err instanceof OauthError) {
1373
+ throw err;
1374
+ }
1329
1375
 
1330
- if (Error.captureStackTrace) {
1331
- Error.captureStackTrace(_assertThisInitialized(_this8), ResourceNotFoundError);
1376
+ throw error;
1377
+ });
1378
+ }
1332
1379
  }
1380
+ }, {
1381
+ key: "_doFetch",
1382
+ value: function _doFetch(accessToken, input, requestParams) {
1383
+ var _this6 = this;
1333
1384
 
1334
- _this8.name = 'ResourceNotFoundError';
1335
- _this8.baseResponse = baseResponse;
1336
- return _this8;
1337
- }
1338
-
1339
- return ResourceNotFoundError;
1340
- }(BadRequestError); // 409
1385
+ var params = requestParams;
1386
+ var baseHeaders = {
1387
+ 'Content-Type': 'application/json'
1388
+ };
1341
1389
 
1390
+ if (accessToken) {
1391
+ baseHeaders.Authorization = "".concat(this.sdk.config.authorizationType, " ").concat(accessToken);
1392
+ }
1342
1393
 
1343
- var ConflictError = /*#__PURE__*/function (_BadRequestError4) {
1344
- _inherits(ConflictError, _BadRequestError4);
1394
+ if (params) {
1395
+ if (!params.headers) {
1396
+ params.headers = {};
1397
+ }
1345
1398
 
1346
- var _super9 = _createSuper(ConflictError);
1399
+ params.headers = Object.assign(baseHeaders, params.headers);
1400
+ } else {
1401
+ params = {
1402
+ headers: baseHeaders
1403
+ };
1404
+ }
1347
1405
 
1348
- function ConflictError(message, baseResponse) {
1349
- var _this9;
1350
-
1351
- _classCallCheck(this, ConflictError);
1352
-
1353
- _this9 = _super9.call(this, message || 'Conflict detected', baseResponse); // Set the prototype explicitly.
1354
-
1355
- _defineProperty(_assertThisInitialized(_this9), "baseResponse", void 0);
1356
-
1357
- Object.setPrototypeOf(_assertThisInitialized(_this9), ConflictError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
1358
-
1359
- if (Error.captureStackTrace) {
1360
- Error.captureStackTrace(_assertThisInitialized(_this9), ConflictError);
1361
- }
1362
-
1363
- _this9.name = 'ConflictError';
1364
- _this9.baseResponse = baseResponse;
1365
- return _this9;
1366
- }
1367
-
1368
- return ConflictError;
1369
- }(BadRequestError); // 500
1370
-
1371
-
1372
- var InternalServerError = /*#__PURE__*/function (_HttpError2) {
1373
- _inherits(InternalServerError, _HttpError2);
1406
+ if (params.headers) {
1407
+ params.headers = removeUndefinedHeaders(params.headers);
1408
+ }
1374
1409
 
1375
- var _super10 = _createSuper(InternalServerError);
1410
+ var logId;
1376
1411
 
1377
- function InternalServerError(message, baseResponse) {
1378
- var _this10;
1412
+ if (this.sdk.logger) {
1413
+ logId = this.sdk.logger.logRequest(_objectSpread2({
1414
+ url: input
1415
+ }, params));
1416
+ } // eslint-disable-next-line consistent-return
1379
1417
 
1380
- _classCallCheck(this, InternalServerError);
1381
1418
 
1382
- _this10 = _super10.call(this, message || 'Internal server error', baseResponse); // Set the prototype explicitly.
1419
+ return fetch(input, params).then(function (response) {
1420
+ if (_this6.sdk.logger) {
1421
+ _this6.sdk.logger.logResponse(response, logId);
1422
+ }
1383
1423
 
1384
- _defineProperty(_assertThisInitialized(_this10), "baseResponse", void 0);
1424
+ if (response.status < 400) {
1425
+ return response;
1426
+ }
1385
1427
 
1386
- Object.setPrototypeOf(_assertThisInitialized(_this10), InternalServerError.prototype); // Maintains proper stack trace for where our error was thrown (only available on V8)
1428
+ if (response.status === 401) {
1429
+ return _this6._manageUnauthorized(response, input, params);
1430
+ }
1387
1431
 
1388
- if (Error.captureStackTrace) {
1389
- Error.captureStackTrace(_assertThisInitialized(_this10), InternalServerError);
1432
+ var httpError = getHttpErrorFromResponse(response);
1433
+ throw httpError;
1434
+ });
1390
1435
  }
1436
+ }, {
1437
+ key: "_getEntityIdentifier",
1438
+ value: function _getEntityIdentifier(object) {
1439
+ var idKey = this.metadata.getIdentifierAttribute().serializedKey; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1440
+ // @ts-ignore
1391
1441
 
1392
- _this10.name = 'InternalServerError';
1393
- _this10.baseResponse = baseResponse;
1394
- return _this10;
1395
- }
1396
-
1397
- return InternalServerError;
1398
- }(HttpError);
1399
- /**
1400
- * @returns {HttpError}
1401
- */
1402
-
1403
-
1404
- function getHttpErrorFromResponse(originalResponse) {
1405
- var response = originalResponse.clone();
1406
-
1407
- switch (true) {
1408
- case response.status === 401:
1409
- return new UnauthorizedError(null, response);
1410
-
1411
- case response.status === 403:
1412
- return new ForbiddenError(null, response);
1413
-
1414
- case response.status === 404:
1415
- return new ResourceNotFoundError(null, response);
1416
-
1417
- case response.status === 409:
1418
- return new ConflictError(null, response);
1419
-
1420
- case response.status >= 400 && response.status < 500:
1421
- return new BadRequestError(null, response);
1422
-
1423
- case response.status >= 500 && response.status < 600:
1424
- return new InternalServerError(null, response);
1442
+ return object[idKey];
1443
+ }
1444
+ }, {
1445
+ key: "_throwIfUnitOfWorkIsDisabled",
1446
+ value: function _throwIfUnitOfWorkIsDisabled() {
1447
+ if (!_classPrivateFieldGet(this, _isUnitOfWorkEnabled)) {
1448
+ throw new Error('UnitOfWork can be deactivated only on find* methods (for now). If you think this should be authorized, please report in https://git.io/JkYTO');
1449
+ }
1450
+ }
1451
+ }]);
1425
1452
 
1426
- default:
1427
- return new HttpError(null, response);
1428
- }
1429
- }
1453
+ return AbstractClient;
1454
+ }();
1430
1455
 
1431
- function isOauthError(body) {
1432
- var _ref;
1456
+ var _attributeList = new WeakMap();
1433
1457
 
1434
- return typeof ((_ref = body) === null || _ref === void 0 ? void 0 : _ref.error) === 'string';
1435
- }
1458
+ var _relationList = new WeakMap();
1436
1459
 
1437
- /* eslint-disable consistent-return */
1438
- function removeAuthorization(headers) {
1439
- if (!headers) {
1440
- return;
1441
- }
1460
+ var _identifierAttribute = new WeakMap();
1442
1461
 
1443
- if (headers instanceof Headers) {
1444
- headers["delete"]('Authorization');
1445
- return headers;
1446
- }
1462
+ var ClassMetadata = /*#__PURE__*/function () {
1463
+ /**
1464
+ * @param {string} key mandatory, will be passed in your serializer
1465
+ * @param {string|null} pathRoot the endpoint of your API: will be added to the mapping prefix ('/v1' here)
1466
+ * @param {typeof AbstractClient} repositoryClass [Overriding repository]{@link https://github.com/mapado/rest-client-js-sdk#overriding-repository} for more detail
1467
+ */
1468
+ function ClassMetadata(key) {
1469
+ var pathRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
1470
+ var repositoryClass = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : AbstractClient;
1447
1471
 
1448
- var filterAuthorization = function filterAuthorization(entries) {
1449
- return entries.filter(function (header) {
1450
- return header[0] !== 'Authorization';
1451
- });
1452
- };
1472
+ _classCallCheck(this, ClassMetadata);
1453
1473
 
1454
- if (Array.isArray(headers)) {
1455
- return filterAuthorization(headers);
1456
- }
1474
+ _defineProperty(this, "key", void 0);
1457
1475
 
1458
- return Object.fromEntries(filterAuthorization(Object.entries(headers)));
1459
- }
1460
- /**
1461
- * remove undefined key, usefull to remove Content-Type for example.
1462
- * Does not apply on "Headers" instance as values are string in there.
1463
- */
1476
+ _defineProperty(this, "pathRoot", void 0);
1464
1477
 
1465
- function removeUndefinedHeaders(headers) {
1466
- if (headers instanceof Headers) {
1467
- return headers;
1468
- }
1478
+ _defineProperty(this, "repositoryClass", void 0);
1469
1479
 
1470
- var filterEntries = function filterEntries(entries) {
1471
- return entries.filter(function (header) {
1472
- return header[1] !== undefined;
1480
+ _attributeList.set(this, {
1481
+ writable: true,
1482
+ value: void 0
1473
1483
  });
1474
- };
1475
-
1476
- if (Array.isArray(headers)) {
1477
- return filterEntries(headers);
1478
- }
1479
-
1480
- return Object.fromEntries(filterEntries(Object.entries(headers)));
1481
- }
1482
-
1483
- var EXPIRE_LIMIT_SECONDS = 300; // = 5 minutes
1484
-
1485
- var _tokenStorage = new WeakMap();
1486
-
1487
- var _isUnitOfWorkEnabled = new WeakMap();
1488
-
1489
- var AbstractClient = /*#__PURE__*/function () {
1490
- function AbstractClient(sdk, metadata) {
1491
- var isUnitOfWorkEnabled = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
1492
-
1493
- _classCallCheck(this, AbstractClient);
1494
-
1495
- _defineProperty(this, "sdk", void 0);
1496
1484
 
1497
- _tokenStorage.set(this, {
1485
+ _relationList.set(this, {
1498
1486
  writable: true,
1499
1487
  value: void 0
1500
1488
  });
1501
1489
 
1502
- _defineProperty(this, "serializer", void 0);
1503
-
1504
- _defineProperty(this, "metadata", void 0);
1505
-
1506
- _isUnitOfWorkEnabled.set(this, {
1490
+ _identifierAttribute.set(this, {
1507
1491
  writable: true,
1508
1492
  value: void 0
1509
1493
  });
1510
1494
 
1511
- this.sdk = sdk;
1495
+ if (!key) {
1496
+ throw new TypeError('key attribute are required');
1497
+ }
1512
1498
 
1513
- _classPrivateFieldSet(this, _tokenStorage, sdk.tokenStorage);
1499
+ this.key = key;
1500
+ this.pathRoot = pathRoot || key; // this.modelName = modelName;
1514
1501
 
1515
- this.serializer = sdk.serializer;
1516
- this.metadata = metadata;
1502
+ this.repositoryClass = repositoryClass;
1517
1503
 
1518
- _classPrivateFieldSet(this, _isUnitOfWorkEnabled, isUnitOfWorkEnabled);
1504
+ _classPrivateFieldSet(this, _attributeList, {});
1505
+
1506
+ _classPrivateFieldSet(this, _relationList, {});
1519
1507
  }
1520
1508
 
1521
- _createClass(AbstractClient, [{
1522
- key: "withUnitOfWork",
1523
- value: function withUnitOfWork(enabled) {
1524
- // eslint-disable-next-line new-cap
1525
- return generateRepository(this.sdk, this.metadata, enabled);
1509
+ _createClass(ClassMetadata, [{
1510
+ key: "getAttribute",
1511
+ value: function getAttribute(name) {
1512
+ return _classPrivateFieldGet(this, _attributeList)[name];
1526
1513
  }
1527
1514
  }, {
1528
- key: "getDefaultParameters",
1529
- value: function getDefaultParameters() {
1530
- return {};
1531
- } // eslint-disable-next-line @typescript-eslint/no-unused-vars
1515
+ key: "hasIdentifierAttribute",
1516
+ value: function hasIdentifierAttribute() {
1517
+ return !!_classPrivateFieldGet(this, _identifierAttribute);
1518
+ }
1519
+ }, {
1520
+ key: "getIdentifierAttribute",
1521
+ value: function getIdentifierAttribute() {
1522
+ if (!_classPrivateFieldGet(this, _identifierAttribute)) {
1523
+ throw new TypeError("\"".concat(this.key, "\" has no identifier attribute set. Did you call \"setAttributeList\" first ?"));
1524
+ }
1532
1525
 
1526
+ return _classPrivateFieldGet(this, _identifierAttribute);
1527
+ }
1533
1528
  }, {
1534
- key: "getPathBase",
1535
- value: function getPathBase(pathParameters) {
1536
- return "/".concat(this.metadata.pathRoot);
1529
+ key: "getAttributeList",
1530
+ value: function getAttributeList() {
1531
+ return _classPrivateFieldGet(this, _attributeList);
1537
1532
  }
1538
1533
  }, {
1539
- key: "getEntityURI",
1540
- value: function getEntityURI(entity) {
1541
- var idValue = this._getEntityIdentifier(entity);
1534
+ key: "setAttributeList",
1535
+ value: function setAttributeList(attributeList) {
1536
+ var _this = this;
1542
1537
 
1543
- if (idValue === null) {
1544
- throw new Error('Cannot call `getEntityURI for entity without id.`');
1545
- }
1538
+ _classPrivateFieldSet(this, _attributeList, {});
1546
1539
 
1547
- if (typeof idValue === 'number') {
1548
- if (Number.isFinite(idValue)) {
1549
- idValue = idValue.toString();
1550
- } else {
1551
- throw new Error('Unable to handle non-finite number');
1552
- }
1553
- }
1540
+ _classPrivateFieldSet(this, _identifierAttribute, undefined);
1554
1541
 
1555
- var pathBase = this.getPathBase({});
1542
+ attributeList.forEach(function (attribute) {
1543
+ _classPrivateFieldGet(_this, _attributeList)[attribute.serializedKey] = attribute;
1556
1544
 
1557
- if (idValue.indexOf(pathBase) > -1) {
1558
- return idValue;
1559
- }
1545
+ if (attribute.isIdentifier) {
1546
+ _classPrivateFieldSet(_this, _identifierAttribute, attribute);
1547
+ }
1548
+ });
1560
1549
 
1561
- return "".concat(pathBase, "/").concat(idValue);
1550
+ if (!_classPrivateFieldGet(this, _identifierAttribute)) {
1551
+ throw new TypeError("\"".concat(this.key, "\" has no identifier attribute set. You must set all your attributes in one time and send an attribute with \"isIdentifier=true\""));
1552
+ }
1562
1553
  }
1563
- /**
1564
- * get an entity by its id
1565
- *
1566
- * @param {string|number} id the entity identifier
1567
- * @param {Record<string, unknown>} queryParam query parameters that will be added to the request
1568
- * @param {Record<string, unknown>} pathParameters path parameters, will be pass to the `getPathBase` method
1569
- * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1570
- */
1571
-
1572
1554
  }, {
1573
- key: "find",
1574
- value: function find(id) {
1575
- var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1576
- var pathParameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1577
- var requestParams = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1555
+ key: "setRelationList",
1556
+ value: function setRelationList(relationList) {
1557
+ var _this2 = this;
1578
1558
 
1579
- var url = this._generateUrlFromParams(queryParam, pathParameters, id);
1559
+ _classPrivateFieldSet(this, _relationList, {});
1580
1560
 
1581
- return this.deserializeResponse(this.authorizedFetch(url, requestParams), 'item');
1561
+ relationList.forEach(function (relation) {
1562
+ _classPrivateFieldGet(_this2, _relationList)[relation.serializedKey] = relation;
1563
+ _classPrivateFieldGet(_this2, _attributeList)[relation.serializedKey] = new Attribute(relation.serializedKey, relation.serializedKey, relation.isRelationToMany() ? 'array' : 'object');
1564
+ });
1582
1565
  }
1583
- /**
1584
- * get a list of entities by some parameters
1585
- *
1586
- * @param {Record<string, unknown>} queryParam query parameters that will be added to the request
1587
- * @param {Record<string, unknown>} pathParameters path parameters, will be pass to the `getPathBase` method
1588
- * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1589
- */
1590
-
1591
1566
  }, {
1592
- key: "findBy",
1593
- value: function findBy(queryParam) {
1594
- var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1595
- var requestParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1596
-
1597
- var url = this._generateUrlFromParams(queryParam, pathParameters);
1598
-
1599
- return this.deserializeResponse(this.authorizedFetch(url, requestParams), 'list');
1567
+ key: "getRelation",
1568
+ value: function getRelation(key) {
1569
+ return _classPrivateFieldGet(this, _relationList)[key];
1600
1570
  }
1601
- /**
1602
- * get a list of all entities
1603
- *
1604
- * @param {Record<string, unknown>} queryParam query parameters that will be added to the request
1605
- * @param {Record<string, unknown>} pathParameters path parameters, will be pass to the `getPathBase` method
1606
- * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1607
- */
1608
-
1609
1571
  }, {
1610
- key: "findAll",
1611
- value: function findAll() {
1612
- var queryParam = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1613
- var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1614
- var requestParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1615
- return this.findBy(queryParam, pathParameters, requestParams);
1572
+ key: "getDefaultSerializedModel",
1573
+ value: function getDefaultSerializedModel() {
1574
+ var _this3 = this;
1575
+
1576
+ var out = {};
1577
+ Object.keys(_classPrivateFieldGet(this, _attributeList)).forEach(function (serializedKey) {
1578
+ out[serializedKey] = null;
1579
+ });
1580
+ Object.keys(_classPrivateFieldGet(this, _relationList)).forEach(function (serializedKey) {
1581
+ var relation = _classPrivateFieldGet(_this3, _relationList)[serializedKey];
1582
+
1583
+ if (relation.isRelationToMany()) {
1584
+ out[serializedKey] = [];
1585
+ }
1586
+ });
1587
+ return out;
1616
1588
  }
1617
- /**
1618
- * create an entity
1619
- *
1620
- * @param {Record<string, unknown>} entity the entity to persist
1621
- * @param {Record<string, unknown>} queryParam query parameters that will be added to the request
1622
- * @param {Record<string, unknown>} pathParameters path parameters, will be pass to the `getPathBase` method
1623
- * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1624
- */
1589
+ }]);
1625
1590
 
1626
- }, {
1627
- key: "create",
1628
- value: function create(entity) {
1629
- var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1630
- var pathParameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1631
- var requestParams = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1591
+ return ClassMetadata;
1592
+ }();
1632
1593
 
1633
- this._throwIfUnitOfWorkIsDisabled();
1594
+ var RelationTypes;
1634
1595
 
1635
- var url = new URI(this.getPathBase(pathParameters));
1636
- url.addSearch(queryParam);
1637
- var oldSerializedModel = this.metadata.getDefaultSerializedModel();
1638
- var newSerializedModel = this.serializer.normalizeItem(entity, this.metadata);
1639
- var diff = this.sdk.unitOfWork.getDirtyData(newSerializedModel, oldSerializedModel, this.metadata);
1640
- return this.deserializeResponse(this.authorizedFetch(url, _objectSpread2({
1641
- method: 'POST',
1642
- body: this.serializer.encodeItem(diff, this.metadata)
1643
- }, requestParams)), 'item');
1644
- }
1645
- /**
1646
- * update an entity
1647
- *
1648
- * @param {Record<string, unknown>} entity the entity to update
1649
- * @param {Record<string, unknown>} queryParam query parameters that will be added to the request
1650
- * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1651
- */
1596
+ (function (RelationTypes) {
1597
+ RelationTypes["ONE_TO_ONE"] = "ONE_TO_ONE";
1598
+ RelationTypes["ONE_TO_MANY"] = "ONE_TO_MANY";
1599
+ RelationTypes["MANY_TO_MANY"] = "MANY_TO_MANY";
1600
+ RelationTypes["MANY_TO_ONE"] = "MANY_TO_ONE";
1601
+ })(RelationTypes || (RelationTypes = {}));
1652
1602
 
1653
- }, {
1654
- key: "update",
1655
- value: function update(entity) {
1656
- var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1657
- var requestParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1603
+ var Relation = /*#__PURE__*/function () {
1604
+ /**
1605
+ * @param {RelationTypes} type the type of relation
1606
+ * @param {string} targetMetadataKey must match the first argument of `ClassMetadata` constructor of the target entity
1607
+ * @param {string} serializedKey the key returned from your API
1608
+ * @param {string|null} attributeName the name in your entity, default to the `serializedKey` attribute
1609
+ */
1610
+ function Relation(type, targetMetadataKey, serializedKey) {
1611
+ var attributeName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
1658
1612
 
1659
- this._throwIfUnitOfWorkIsDisabled();
1613
+ _classCallCheck(this, Relation);
1660
1614
 
1661
- var url = new URI(this.getEntityURI(entity));
1662
- url.addSearch(queryParam);
1663
- var newSerializedModel = this.serializer.normalizeItem(entity, this.metadata);
1615
+ _defineProperty(this, "type", void 0);
1664
1616
 
1665
- var identifier = this._getEntityIdentifier(newSerializedModel);
1617
+ _defineProperty(this, "targetMetadataKey", void 0);
1666
1618
 
1667
- var oldModel;
1619
+ _defineProperty(this, "serializedKey", void 0);
1668
1620
 
1669
- if (identifier !== null) {
1670
- oldModel = this.sdk.unitOfWork.getDirtyEntity(identifier);
1671
- }
1621
+ _defineProperty(this, "attributeName", void 0);
1672
1622
 
1673
- if (oldModel) {
1674
- newSerializedModel = this.sdk.unitOfWork.getDirtyData(newSerializedModel, oldModel, this.metadata);
1675
- }
1623
+ this.type = type;
1624
+ this.targetMetadataKey = targetMetadataKey;
1625
+ this.serializedKey = serializedKey;
1626
+ this.attributeName = attributeName || this.serializedKey;
1627
+ }
1676
1628
 
1677
- return this.deserializeResponse(this.authorizedFetch(url, _objectSpread2({
1678
- method: 'PUT',
1679
- body: this.serializer.encodeItem(newSerializedModel, this.metadata)
1680
- }, requestParams)), 'item');
1629
+ _createClass(Relation, [{
1630
+ key: "isOneToOne",
1631
+ value: function isOneToOne() {
1632
+ return this.type === Relation.ONE_TO_ONE;
1681
1633
  }
1682
- /**
1683
- * delete an entity
1684
- *
1685
- * @param {Record<string, unknown>} the entity to delete
1686
- * @param {Record<string, unknown>} requestParams parameters that will be send as second parameter to the `fetch` call
1687
- */
1688
-
1689
1634
  }, {
1690
- key: "delete",
1691
- value: function _delete(entity) {
1692
- var _this = this;
1635
+ key: "isOneToMany",
1636
+ value: function isOneToMany() {
1637
+ return this.type === Relation.ONE_TO_MANY;
1638
+ }
1639
+ }, {
1640
+ key: "isManyToOne",
1641
+ value: function isManyToOne() {
1642
+ return this.type === Relation.MANY_TO_ONE;
1643
+ }
1644
+ }, {
1645
+ key: "isManyToMany",
1646
+ value: function isManyToMany() {
1647
+ return this.type === Relation.MANY_TO_MANY;
1648
+ }
1649
+ }, {
1650
+ key: "isRelationToMany",
1651
+ value: function isRelationToMany() {
1652
+ return this.isManyToMany() || this.isOneToMany();
1653
+ }
1654
+ }, {
1655
+ key: "isRelationToOne",
1656
+ value: function isRelationToOne() {
1657
+ return this.isManyToOne() || this.isOneToOne();
1658
+ }
1659
+ }]);
1693
1660
 
1694
- var requestParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1661
+ return Relation;
1662
+ }();
1695
1663
 
1696
- this._throwIfUnitOfWorkIsDisabled();
1664
+ _defineProperty(Relation, "ONE_TO_ONE", RelationTypes.ONE_TO_ONE);
1697
1665
 
1698
- var url = this.getEntityURI(entity);
1666
+ _defineProperty(Relation, "ONE_TO_MANY", RelationTypes.ONE_TO_MANY);
1699
1667
 
1700
- var identifier = this._getEntityIdentifier(entity);
1668
+ _defineProperty(Relation, "MANY_TO_ONE", RelationTypes.MANY_TO_ONE);
1701
1669
 
1702
- return this.authorizedFetch(url, _objectSpread2({
1703
- method: 'DELETE'
1704
- }, requestParams)).then(function (response) {
1705
- if (identifier !== null) {
1706
- _this.sdk.unitOfWork.clear(identifier);
1707
- }
1670
+ _defineProperty(Relation, "MANY_TO_MANY", RelationTypes.MANY_TO_MANY);
1708
1671
 
1709
- return response;
1710
- });
1711
- }
1712
- }, {
1713
- key: "deserializeResponse",
1714
- value: function deserializeResponse(requestPromise, listOrItem) {
1715
- var _this2 = this;
1672
+ /* eslint-disable */
1673
+ // "fork" of https://github.com/facebook/immutable-js/blob/v4.0.0-rc.9/src/Predicates.js
1674
+ // because tree-shaking does not seems to work as expected
1716
1675
 
1717
- return requestPromise.then(function (response) {
1718
- return response.text().then(function (text) {
1719
- return {
1720
- response: response,
1721
- text: text
1722
- };
1723
- });
1724
- }).then(function (_ref) {
1725
- var response = _ref.response,
1726
- text = _ref.text;
1676
+ /**
1677
+ * Copyright (c) 2014-present, Facebook, Inc.
1678
+ *
1679
+ * This source code is licensed under the MIT license found in the
1680
+ * LICENSE file in the root directory of this source tree.
1681
+ */
1682
+ var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
1683
+ var IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@';
1684
+ function isImmutable(maybeImmutable) {
1685
+ return isCollection(maybeImmutable) || isRecord(maybeImmutable);
1686
+ }
1687
+ function isCollection(maybeCollection) {
1688
+ return !!(maybeCollection && maybeCollection[IS_ITERABLE_SENTINEL]);
1689
+ }
1690
+ function isRecord(maybeRecord) {
1691
+ return !!(maybeRecord && maybeRecord[IS_RECORD_SENTINEL]);
1692
+ }
1727
1693
 
1728
- if (listOrItem === 'list') {
1729
- // for list, we need to deserialize the result to get an object
1730
- var itemList = _this2.serializer.deserializeList(text, _this2.metadata, response); // eslint-disable-next-line no-restricted-syntax
1694
+ /**
1695
+ * deep comparaison between objects
1696
+ */
1697
+ function objectDiffers(left, right) {
1698
+ var result = deepDiff.diff(left, right);
1699
+ return result ? result.length > 0 : false;
1700
+ }
1701
+ /**
1702
+ * get the id of an entity or return itself if string
1703
+ */
1731
1704
 
1732
1705
 
1733
- var _iterator = _createForOfIteratorHelper(itemList),
1734
- _step;
1706
+ function getEntityId(stringOrEntity, idSerializedKey) {
1707
+ if (_typeof(stringOrEntity) !== 'object') {
1708
+ return stringOrEntity;
1709
+ } // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1710
+ // @ts-ignore
1735
1711
 
1736
- try {
1737
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1738
- var _decodedItem = _step.value;
1739
1712
 
1740
- var _identifier = _this2._getEntityIdentifier(_decodedItem);
1713
+ return stringOrEntity[idSerializedKey];
1714
+ }
1715
+ /**
1716
+ * find old relation value from the new relation id
1717
+ * if not found, returs the default serilazed model
1718
+ */
1741
1719
 
1742
- var normalizedItem = _this2.serializer.normalizeItem(_decodedItem, _this2.metadata); // then we register the re-normalized item
1743
1720
 
1721
+ function findOldRelation(newRelationValue, oldRelationValue, classMetadata) {
1722
+ var idSerializedKey = classMetadata.getIdentifierAttribute().serializedKey; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1723
+ // @ts-ignore
1744
1724
 
1745
- if (_classPrivateFieldGet(_this2, _isUnitOfWorkEnabled) && _identifier !== null) {
1746
- _this2.sdk.unitOfWork.registerClean(_identifier, normalizedItem);
1747
- }
1748
- }
1749
- } catch (err) {
1750
- _iterator.e(err);
1751
- } finally {
1752
- _iterator.f();
1753
- }
1725
+ var relationValueId = getEntityId(newRelationValue, idSerializedKey);
1726
+ var foundValue = oldRelationValue && oldRelationValue.find(function (innerOldRelationValue) {
1727
+ var oldRelationValueId = getEntityId(innerOldRelationValue, idSerializedKey);
1728
+ return relationValueId === oldRelationValueId;
1729
+ });
1754
1730
 
1755
- return itemList;
1756
- } // for items, we can just decode the item (ie. transform it to JS object)
1731
+ if (foundValue) {
1732
+ return foundValue;
1733
+ }
1757
1734
 
1735
+ return classMetadata.getDefaultSerializedModel();
1736
+ }
1737
+ /**
1738
+ * add all identifier from one to many relation list
1739
+ */
1758
1740
 
1759
- var decodedItem = _this2.serializer.decodeItem(text, _this2.metadata, response); // and register it directy without deserializing + renormalizing
1760
1741
 
1742
+ function getIdentifierForList(newValue, idSerializedKey) {
1743
+ return newValue.map(function (value) {
1744
+ if (Object.keys(value).includes(idSerializedKey)) {
1745
+ return _defineProperty({}, idSerializedKey, value[idSerializedKey]);
1746
+ }
1761
1747
 
1762
- var identifier = _this2._getEntityIdentifier(decodedItem); // and finally return the denormalized item
1748
+ if (typeof value === 'string') {
1749
+ return value;
1750
+ }
1763
1751
 
1752
+ throw new TypeError('new value should include a list of string or objects containing the serialized key');
1753
+ });
1754
+ }
1764
1755
 
1765
- var item = _this2.serializer.denormalizeItem(decodedItem, _this2.metadata, response);
1756
+ var _storage = new WeakMap();
1766
1757
 
1767
- if (_classPrivateFieldGet(_this2, _isUnitOfWorkEnabled) && identifier !== null) {
1768
- _this2.sdk.unitOfWork.registerClean(identifier, _this2.serializer.normalizeItem(item, _this2.metadata));
1769
- }
1758
+ var _enabled = new WeakMap();
1770
1759
 
1771
- return item;
1772
- });
1773
- }
1774
- }, {
1775
- key: "makeUri",
1776
- value: function makeUri(input) {
1777
- var url = input instanceof URI ? input : new URI(input);
1778
- url.host(this.sdk.config.path).scheme(this.sdk.config.scheme);
1760
+ var UnitOfWork = /*#__PURE__*/function () {
1761
+ function UnitOfWork(mapping) {
1762
+ var enabled = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
1779
1763
 
1780
- if (this.sdk.config.port) {
1781
- url.port(String(this.sdk.config.port));
1782
- }
1764
+ _classCallCheck(this, UnitOfWork);
1783
1765
 
1784
- if (this.sdk.mapping.idPrefix) {
1785
- var segments = url.segment();
1766
+ _defineProperty(this, "mapping", void 0);
1786
1767
 
1787
- if (!url.pathname().startsWith(this.sdk.mapping.idPrefix)) {
1788
- segments.unshift(this.sdk.mapping.idPrefix);
1789
- url.segment(segments);
1790
- }
1768
+ _storage.set(this, {
1769
+ writable: true,
1770
+ value: void 0
1771
+ });
1772
+
1773
+ _enabled.set(this, {
1774
+ writable: true,
1775
+ value: void 0
1776
+ });
1777
+
1778
+ this.mapping = mapping;
1779
+
1780
+ _classPrivateFieldSet(this, _enabled, enabled);
1781
+
1782
+ _classPrivateFieldSet(this, _storage, {});
1783
+ }
1784
+
1785
+ _createClass(UnitOfWork, [{
1786
+ key: "registerClean",
1787
+ value: function registerClean(id, entity) {
1788
+ if (!_classPrivateFieldGet(this, _enabled)) {
1789
+ return;
1791
1790
  }
1792
1791
 
1793
- return url;
1792
+ if (isImmutable(entity)) {
1793
+ _classPrivateFieldGet(this, _storage)[id] = entity;
1794
+ } else {
1795
+ _classPrivateFieldGet(this, _storage)[id] = _objectSpread2({}, entity);
1796
+ }
1794
1797
  }
1795
1798
  }, {
1796
- key: "authorizedFetch",
1797
- value: function authorizedFetch(input) {
1798
- var requestParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1799
- var url = this.makeUri(input);
1800
- return this._fetchWithToken(url.toString(), requestParams);
1799
+ key: "getDirtyEntity",
1800
+ value: function getDirtyEntity(id) {
1801
+ return _classPrivateFieldGet(this, _storage)[id];
1801
1802
  }
1802
1803
  }, {
1803
- key: "_generateUrlFromParams",
1804
- value: function _generateUrlFromParams(queryParam) {
1805
- var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1806
- var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
1807
- var params = queryParam;
1804
+ key: "clear",
1805
+ value: function clear(id) {
1806
+ delete _classPrivateFieldGet(this, _storage)[id];
1807
+ }
1808
+ }, {
1809
+ key: "getDirtyData",
1810
+ value: function getDirtyData(newSerializedModel, oldSerializedModel, classMetadata) {
1811
+ return this._getDirtyFields(newSerializedModel, oldSerializedModel, classMetadata);
1812
+ }
1813
+ }, {
1814
+ key: "_getDirtyFieldsForAttribute",
1815
+ value: function _getDirtyFieldsForAttribute(dirtyFieldsParam, key, attribute, oldValue, newValue) {
1816
+ var dirtyFields = dirtyFieldsParam;
1808
1817
 
1809
- if (this.sdk.config.useDefaultParameters) {
1810
- Object.assign(params, this.getDefaultParameters());
1818
+ if (attribute.type === 'object') {
1819
+ if (oldValue === undefined || objectDiffers(oldValue, newValue)) {
1820
+ dirtyFields[key] = newValue;
1821
+ }
1822
+ } else if (oldValue !== newValue) {
1823
+ dirtyFields[key] = newValue;
1811
1824
  }
1812
1825
 
1813
- var pathBase = this.getPathBase(pathParameters);
1814
- var url = null;
1826
+ return dirtyFields;
1827
+ }
1828
+ }, {
1829
+ key: "_getDirtyFieldsForManyToOne",
1830
+ value: function _getDirtyFieldsForManyToOne(dirtyFieldsParam, key, oldValue, newValue, relationMetadata, idSerializedKey) {
1831
+ var dirtyFields = dirtyFieldsParam;
1815
1832
 
1816
- if (id) {
1817
- var testPathBase = this.sdk.mapping.idPrefix ? "".concat(this.sdk.mapping.idPrefix).concat(pathBase) : pathBase;
1833
+ if (oldValue !== newValue) {
1834
+ if (newValue === null) {
1835
+ dirtyFields[key] = null;
1836
+ return dirtyFields;
1837
+ }
1818
1838
 
1819
- if (typeof id === 'string' && id.startsWith(testPathBase)) {
1820
- url = new URI(id);
1821
- } else {
1822
- url = new URI("".concat(pathBase, "/").concat(id));
1839
+ if (typeof oldValue === 'string' || typeof newValue === 'string') {
1840
+ dirtyFields[key] = newValue;
1823
1841
  }
1824
- } else {
1825
- url = new URI(pathBase);
1826
- }
1827
1842
 
1828
- if (params) {
1829
- url.addSearch(params);
1843
+ var recursiveDiff = this._getDirtyFields(newValue, oldValue, relationMetadata);
1844
+
1845
+ if (Object.keys(recursiveDiff).length > 0) {
1846
+ recursiveDiff[idSerializedKey] = getEntityId(newValue, idSerializedKey);
1847
+ dirtyFields[key] = recursiveDiff;
1848
+ }
1830
1849
  }
1831
1850
 
1832
- return url;
1851
+ return dirtyFields;
1833
1852
  }
1834
1853
  }, {
1835
- key: "_fetchWithToken",
1836
- value: function _fetchWithToken(input) {
1837
- var _this3 = this;
1854
+ key: "_getDirtyFieldsForOneToMany",
1855
+ value: function _getDirtyFieldsForOneToMany(dirtyFieldsParam, key, idSerializedKey, relationMetadata, oldValue, newValue) {
1856
+ var _this = this;
1838
1857
 
1839
- var requestParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1858
+ var dirtyFields = dirtyFieldsParam;
1859
+ var newValueLength = newValue ? newValue.length : 0;
1860
+ var oldValueLength = oldValue ? oldValue.length : 0; // number of items changed
1840
1861
 
1841
- if (!input) {
1842
- throw new Error('input is empty');
1862
+ if (newValueLength !== oldValueLength) {
1863
+ dirtyFields[key] = getIdentifierForList(newValue, idSerializedKey);
1843
1864
  }
1844
1865
 
1845
- if (_classPrivateFieldGet(this, _tokenStorage)) {
1846
- return _classPrivateFieldGet(this, _tokenStorage).getCurrentTokenExpiresIn().then(function (accessTokenExpiresIn) {
1847
- if (accessTokenExpiresIn !== null && accessTokenExpiresIn <= EXPIRE_LIMIT_SECONDS) {
1848
- return _classPrivateFieldGet(_this3, _tokenStorage).refreshToken().then(function (refreshedTokenObject) {
1849
- return refreshedTokenObject.access_token;
1850
- });
1851
- }
1866
+ if (newValue && newValue.length > 0) {
1867
+ if (dirtyFields[key] === undefined) {
1868
+ dirtyFields[key] = [];
1869
+ }
1852
1870
 
1853
- return _classPrivateFieldGet(_this3, _tokenStorage).getAccessToken();
1854
- }).then(function (token) {
1855
- return _this3._doFetch(token, input, requestParams);
1856
- });
1857
- }
1871
+ var relationList = newValue;
1872
+ relationList.forEach(function (newRelationValue, relationAttributeName) {
1873
+ var oldRelationValue = findOldRelation(newRelationValue, oldValue, relationMetadata);
1858
1874
 
1859
- return this._doFetch(null, input, requestParams);
1860
- }
1861
- }, {
1862
- key: "_refreshTokenAndRefetch",
1863
- value: function _refreshTokenAndRefetch(input) {
1864
- var _this4 = this;
1875
+ if (newRelationValue !== oldRelationValue) {
1876
+ if (typeof newRelationValue === 'string' || typeof oldRelationValue === 'string') {
1877
+ dirtyFields[key][relationAttributeName] = newRelationValue;
1878
+ return;
1879
+ }
1865
1880
 
1866
- var requestParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1867
- return _classPrivateFieldGet(this, _tokenStorage).refreshToken().then(function () {
1868
- // eslint-disable-next-line prefer-const
1869
- var headers = requestParams.headers,
1870
- rest = _objectWithoutProperties(requestParams, ["headers"]);
1881
+ var recursiveDiff = _this._getDirtyFields(newRelationValue, oldRelationValue, relationMetadata);
1871
1882
 
1872
- var updatedRequestParams = _objectSpread2(_objectSpread2({}, rest), {}, {
1873
- headers: removeAuthorization(headers)
1883
+ if (Object.keys(recursiveDiff).length > 0) {
1884
+ var entityId = getEntityId(newRelationValue, idSerializedKey);
1885
+
1886
+ if (entityId !== null) {
1887
+ recursiveDiff[idSerializedKey] = entityId;
1888
+ }
1889
+
1890
+ if (dirtyFields[key][relationAttributeName]) {
1891
+ Object.assign(dirtyFields[key][relationAttributeName], recursiveDiff);
1892
+ } else {
1893
+ dirtyFields[key][relationAttributeName] = recursiveDiff;
1894
+ }
1895
+ }
1896
+ }
1874
1897
  });
1875
1898
 
1876
- return _this4._fetchWithToken(input, updatedRequestParams);
1877
- });
1899
+ if (dirtyFields[key].length > 0) {
1900
+ // add identifier because one or more object linked has been updated
1901
+ // see test: 'get dirty data many to one update item'
1902
+ dirtyFields[key] = Object.assign(getIdentifierForList(newValue, idSerializedKey), dirtyFields[key]);
1903
+ } else {
1904
+ // no changes, no need to send the key with an empty array as value
1905
+ delete dirtyFields[key];
1906
+ }
1907
+ }
1908
+
1909
+ return dirtyFields;
1878
1910
  }
1879
1911
  }, {
1880
- key: "_manageUnauthorized",
1881
- value: function _manageUnauthorized(response, input) {
1882
- var _this5 = this;
1912
+ key: "_getDirtyFields",
1913
+ value: function _getDirtyFields(newSerializedModel, oldSerializedModel, classMetadata) {
1914
+ var _this2 = this;
1883
1915
 
1884
- var requestParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1885
- var error = getHttpErrorFromResponse(response); // https://tools.ietf.org/html/rfc2617#section-1.2
1916
+ var dirtyFields = {};
1917
+ Object.values(classMetadata.getAttributeList()).forEach(function (attribute) {
1918
+ var key = attribute.attributeName;
1919
+ var newValue = newSerializedModel[key];
1920
+ var oldValue = oldSerializedModel ? oldSerializedModel[key] : null;
1921
+ var currentRelation = classMetadata.getRelation(attribute.serializedKey);
1886
1922
 
1887
- var authorizationHeader = response.headers.get('www-authenticate');
1923
+ if (newValue === undefined) {
1924
+ return;
1925
+ } // not a relation
1888
1926
 
1889
- if (authorizationHeader) {
1890
- var invalidGrant = authorizationHeader.indexOf('error = "invalid_grant"');
1891
1927
 
1892
- if (invalidGrant && _classPrivateFieldGet(this, _tokenStorage)) {
1893
- return this._refreshTokenAndRefetch(input, requestParams);
1928
+ if (!currentRelation) {
1929
+ dirtyFields = _this2._getDirtyFieldsForAttribute(dirtyFields, key, attribute, oldValue, newValue);
1930
+ return;
1894
1931
  }
1895
1932
 
1896
- throw error;
1897
- } else {
1898
- // if www-authenticate header is missing, try and read json response
1899
- return response.json().then(function (body) {
1900
- if (_classPrivateFieldGet(_this5, _tokenStorage) && body.error === 'invalid_grant') {
1901
- return _this5._refreshTokenAndRefetch(input, requestParams);
1902
- }
1933
+ var relationMetadata = _this2.mapping.getClassMetadataByKey(currentRelation.targetMetadataKey);
1903
1934
 
1904
- throw error;
1905
- })["catch"](function (err) {
1906
- if (err instanceof OauthError) {
1907
- throw err;
1908
- }
1935
+ if (!relationMetadata) {
1936
+ throw new TypeError("relation metadata is not set for relation ".concat(classMetadata.key, ".").concat(currentRelation.targetMetadataKey));
1937
+ }
1909
1938
 
1910
- throw error;
1911
- });
1912
- }
1913
- }
1914
- }, {
1915
- key: "_doFetch",
1916
- value: function _doFetch(accessToken, input, requestParams) {
1917
- var _this6 = this;
1939
+ var idSerializedKey = relationMetadata.getIdentifierAttribute().serializedKey; // MANY_TO_ONE relation
1918
1940
 
1919
- var params = requestParams;
1920
- var baseHeaders = {
1921
- 'Content-Type': 'application/json'
1922
- };
1941
+ if (currentRelation.isRelationToOne()) {
1942
+ dirtyFields = _this2._getDirtyFieldsForManyToOne(dirtyFields, key, oldValue, newValue, relationMetadata, idSerializedKey);
1943
+ return;
1944
+ } // *_TO_MANY relation
1923
1945
 
1924
- if (accessToken) {
1925
- baseHeaders.Authorization = "".concat(this.sdk.config.authorizationType, " ").concat(accessToken);
1926
- }
1927
1946
 
1928
- var currentUri = (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object' && window.location && window.location.href;
1947
+ dirtyFields = _this2._getDirtyFieldsForOneToMany(dirtyFields, key, idSerializedKey, relationMetadata, oldValue, newValue);
1948
+ });
1949
+ return dirtyFields;
1950
+ }
1951
+ }]);
1929
1952
 
1930
- if (currentUri) {
1931
- baseHeaders.Referer = currentUri;
1932
- }
1953
+ return UnitOfWork;
1954
+ }();
1933
1955
 
1934
- if (params) {
1935
- if (!params.headers) {
1936
- params.headers = {};
1937
- }
1956
+ /* eslint-disable @typescript-eslint/no-unused-vars */
1957
+ var Serializer = /*#__PURE__*/function () {
1958
+ function Serializer() {
1959
+ _classCallCheck(this, Serializer);
1960
+ }
1938
1961
 
1939
- params.headers = Object.assign(baseHeaders, params.headers);
1940
- } else {
1941
- params = {
1942
- headers: baseHeaders
1943
- };
1944
- }
1962
+ _createClass(Serializer, [{
1963
+ key: "normalizeItem",
1945
1964
 
1946
- if (params.headers) {
1947
- params.headers = removeUndefinedHeaders(params.headers);
1948
- } // eslint-disable-next-line consistent-return
1965
+ /**
1966
+ * convert an entity to a plain javascript object
1967
+ * @param {object} entity - The entity to convert
1968
+ * @param {ClassMetadata} classMetadata - the class metadata
1969
+ * @return {object} the object to serialize
1970
+ */
1971
+ value: function normalizeItem(entity, classMetadata) {
1972
+ return entity;
1973
+ }
1974
+ /**
1975
+ * convert a plain javascript object to string
1976
+ * @param {object} object - The object to convert to convert
1977
+ * @param {ClassMetadata} classMetadata - the class metadata
1978
+ * @return {string} the content of the request
1979
+ */
1949
1980
 
1981
+ }, {
1982
+ key: "encodeItem",
1983
+ value: function encodeItem(object, classMetadata) {
1984
+ throw new TypeError('`encodeItem` method must be implemented');
1985
+ }
1986
+ /**
1987
+ * convert an entity to string that will be sent as the request content
1988
+ * @param {any} entity - The entity to convert
1989
+ * @param {ClassMetadata} classMetadata - the class metadata
1990
+ * @return {string} the content of the request
1991
+ */
1950
1992
 
1951
- return fetch(input, params).then(function (response) {
1952
- if (response.status < 400) {
1953
- return response;
1954
- }
1993
+ }, {
1994
+ key: "serializeItem",
1995
+ value: function serializeItem(object, classMetadata) {
1996
+ var noralizedData = this.normalizeItem(object, classMetadata);
1997
+ return this.encodeItem(noralizedData, classMetadata);
1998
+ }
1999
+ /**
2000
+ * convert a plain object to an entity
2001
+ * @param {object} object - The plain javascript object
2002
+ * @param {ClassMetadata} classMetadata - the class metadata
2003
+ * @param {Record<string, unknown>} response - the HTTP response
2004
+ * @return {object} an entity
2005
+ */
1955
2006
 
1956
- if (response.status === 401) {
1957
- return _this6._manageUnauthorized(response, input, params);
1958
- }
2007
+ }, {
2008
+ key: "denormalizeItem",
2009
+ value: function denormalizeItem(object, classMetadata, response) {
2010
+ return object;
2011
+ }
2012
+ /**
2013
+ * convert a string containing an object to a plain javascript object
2014
+ * @param {string} rawData - The string fetched from the response
2015
+ * @param {ClassMetadata} classMetadata - the class metadata
2016
+ * @param {Record<string, unknown>} response - the HTTP response
2017
+ * @return {object} the normalized object
2018
+ */
2019
+
2020
+ }, {
2021
+ key: "decodeItem",
2022
+ value: function decodeItem(rawData, classMetadata, response) {
2023
+ throw new TypeError('`decodeItem` method must be implemented');
2024
+ }
2025
+ /**
2026
+ * convert a string containing an object to an entity
2027
+ * @param {string} rawData - The string fetched from the response
2028
+ * @param {ClassMetadata} classMetadata - the class metadata
2029
+ * @param {Record<string, unknown>} response - the HTTP response
2030
+ * @return {object} the entity
2031
+ */
1959
2032
 
1960
- var httpError = getHttpErrorFromResponse(response);
1961
- throw httpError;
1962
- });
2033
+ }, {
2034
+ key: "deserializeItem",
2035
+ value: function deserializeItem(rawData, classMetadata, response) {
2036
+ var object = this.decodeItem(rawData, classMetadata, response);
2037
+ return this.denormalizeItem(object, classMetadata, response);
1963
2038
  }
2039
+ /**
2040
+ * convert a plain object list to an entity list
2041
+ * @param {Iterable<object>} objectList - The plain javascript object list (or an iterable object)
2042
+ * @param {ClassMetadata} classMetadata - the class metadata
2043
+ * @param {Record<string, unknown>} response - the HTTP response
2044
+ * @return {Iterable<object>} a list of entities
2045
+ */
2046
+
1964
2047
  }, {
1965
- key: "_getEntityIdentifier",
1966
- value: function _getEntityIdentifier(object) {
1967
- var idKey = this.metadata.getIdentifierAttribute().serializedKey; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1968
- // @ts-ignore
2048
+ key: "denormalizeList",
2049
+ value: function denormalizeList(objectList, classMetadata, response) {
2050
+ return objectList; // weird conversion as the declaration of list type is fuzzy
2051
+ }
2052
+ /**
2053
+ * convert a string containing a list of objects to a list of plain javascript objects
2054
+ * @param {string} rawListData - The string fetched from the response
2055
+ * @param {ClassMetadata} classMetadata - the class metadata
2056
+ * @param {Record<string, unknown>} response - the HTTP response
2057
+ * @return {Iterable<object>} a list of normalized objects
2058
+ */
1969
2059
 
1970
- return object[idKey];
2060
+ }, {
2061
+ key: "decodeList",
2062
+ value: function decodeList(rawListData, classMetadata, response) {
2063
+ throw new TypeError('`deserializeList` method must be implemented');
1971
2064
  }
2065
+ /**
2066
+ * convert a string containing a list of objects to a list of entities
2067
+ * @param {string} rawListData - The string fetched from the response
2068
+ * @param {ClassMetadata} classMetadata - the class metadata
2069
+ * @param {Record<string, unknown>} response - the HTTP response
2070
+ * @return {Iterable<object>} a list of entities
2071
+ */
2072
+
1972
2073
  }, {
1973
- key: "_throwIfUnitOfWorkIsDisabled",
1974
- value: function _throwIfUnitOfWorkIsDisabled() {
1975
- if (!_classPrivateFieldGet(this, _isUnitOfWorkEnabled)) {
1976
- throw new Error('UnitOfWork can be deactivated only on find* methods (for now). If you think this should be authorized, please report in https://git.io/JkYTO');
1977
- }
2074
+ key: "deserializeList",
2075
+ value: function deserializeList(rawListData, classMetadata, response) {
2076
+ var objectList = this.decodeList(rawListData, classMetadata, response);
2077
+ return this.denormalizeList(objectList, classMetadata, response);
1978
2078
  }
1979
2079
  }]);
1980
2080
 
1981
- return AbstractClient;
2081
+ return Serializer;
1982
2082
  }();
1983
2083
 
1984
- /* eslint-disable import/prefer-default-export */
1985
- // memoize promise returning function so that it returns
1986
- // the same promise if called again before resolve / reject
1987
- function memoizePromise(callback) {
1988
- var cache = {};
1989
-
1990
- function memoized() {
1991
- for (var _len = arguments.length, parameters = new Array(_len), _key = 0; _key < _len; _key++) {
1992
- parameters[_key] = arguments[_key];
1993
- }
1994
-
1995
- var cacheKey = JSON.stringify(parameters);
1996
- var cacheValue = cache[cacheKey];
1997
-
1998
- if (cacheValue) {
1999
- return cacheValue;
2000
- } // Get and add the value to the cache
2001
-
2002
-
2003
- var value = callback.apply(this, parameters);
2004
- cache[cacheKey] = value;
2005
-
2006
- if (!value || typeof value.then !== 'function') {
2007
- throw new Error('Memoization Error, Async function returned non-promise value');
2008
- } // Delete the value regardless of whether it resolves or rejects
2009
-
2010
-
2011
- return value.then(function (internalValue) {
2012
- cache[cacheKey] = false;
2013
- return internalValue;
2014
- }, function (err) {
2015
- cache[cacheKey] = false;
2016
- throw err;
2017
- });
2018
- }
2019
-
2020
- memoized.cache = cache;
2021
- return memoized;
2022
- }
2023
-
2024
- function isResponse(response) {
2025
- return typeof (response === null || response === void 0 ? void 0 : response.json) === 'function';
2026
- }
2084
+ var JsSerializer = /*#__PURE__*/function (_Serializer) {
2085
+ _inherits(JsSerializer, _Serializer);
2027
2086
 
2028
- function manageOauthError(body, response) {
2029
- var error;
2087
+ var _super = _createSuper(JsSerializer);
2030
2088
 
2031
- if (response) {
2032
- error = getHttpErrorFromResponse(response);
2033
- }
2089
+ function JsSerializer() {
2090
+ _classCallCheck(this, JsSerializer);
2034
2091
 
2035
- if (body.error === 'invalid_grant') {
2036
- throw new InvalidGrantError(body.error, error);
2092
+ return _super.apply(this, arguments);
2037
2093
  }
2038
2094
 
2039
- if (body.error === 'invalid_scope') {
2040
- throw new InvalidScopeError(body.error, error);
2041
- }
2095
+ _createClass(JsSerializer, [{
2096
+ key: "encodeItem",
2097
+ value: function encodeItem(object, classMetadata) {
2098
+ return JSON.stringify(object);
2099
+ }
2100
+ }, {
2101
+ key: "decodeItem",
2102
+ value: function decodeItem(rawData, classMetadata, response) {
2103
+ return JSON.parse(rawData);
2104
+ }
2105
+ }, {
2106
+ key: "decodeList",
2107
+ value: function decodeList(rawListData, classMetadata, response) {
2108
+ return JSON.parse(rawListData);
2109
+ }
2110
+ }]);
2042
2111
 
2043
- throw new OauthError(body.error, error);
2044
- }
2112
+ return JsSerializer;
2113
+ }(Serializer);
2045
2114
 
2046
- var _tokenGenerator = new WeakMap();
2115
+ var generateId = function generateId() {
2116
+ return "rest-client-sdk|".concat(Date.now(), "-").concat(Math.floor(Math.random() * (9e12 - 1)) + 1e12);
2117
+ };
2047
2118
 
2048
- var _hasATokenBeenGenerated = new WeakMap();
2119
+ function serializeRequest(req) {
2120
+ var request = _objectSpread2({}, req); // Make a clone, useful for doing destructive things
2049
2121
 
2050
- var _asyncStorage = new WeakMap();
2051
2122
 
2052
- var TokenStorage = /*#__PURE__*/function () {
2053
- function TokenStorage(tokenGenerator, asyncStorage) {
2054
- var accessTokenKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'rest_client_sdk.api.access_token';
2123
+ return {
2124
+ method: request.method,
2125
+ // The Request Method, e.g. GET, POST, DELETE
2126
+ url: request.url,
2127
+ // The URL
2128
+ headers: request.headers ? convertToRecord(request.headers) : undefined,
2129
+ body: typeof request.body === 'string' ? request.body : undefined
2130
+ };
2131
+ } // eslint-disable-next-line import/prefer-default-export
2055
2132
 
2056
- _classCallCheck(this, TokenStorage);
2057
2133
 
2058
- _tokenGenerator.set(this, {
2059
- writable: true,
2060
- value: void 0
2061
- });
2134
+ var _history = new WeakMap();
2062
2135
 
2063
- _hasATokenBeenGenerated.set(this, {
2064
- writable: true,
2065
- value: void 0
2066
- });
2136
+ var Logger = /*#__PURE__*/function () {
2137
+ _createClass(Logger, [{
2138
+ key: "history",
2139
+ get: function get() {
2140
+ return _classPrivateFieldGet(this, _history);
2141
+ }
2142
+ }]);
2067
2143
 
2068
- _defineProperty(this, "accessTokenKey", void 0);
2144
+ function Logger() {
2145
+ _classCallCheck(this, Logger);
2069
2146
 
2070
- _asyncStorage.set(this, {
2147
+ _history.set(this, {
2071
2148
  writable: true,
2072
2149
  value: void 0
2073
2150
  });
2074
2151
 
2075
- _classPrivateFieldSet(this, _tokenGenerator, tokenGenerator);
2152
+ _classPrivateFieldSet(this, _history, []);
2153
+ }
2076
2154
 
2077
- _classPrivateFieldSet(this, _hasATokenBeenGenerated, false);
2155
+ _createClass(Logger, [{
2156
+ key: "logRequest",
2157
+ value: function logRequest(params) {
2158
+ var log = {
2159
+ id: generateId(),
2160
+ request: serializeRequest(params),
2161
+ logTimes: {
2162
+ request: Date.now()
2163
+ }
2164
+ };
2078
2165
 
2079
- this.setAsyncStorage(asyncStorage);
2080
- this.accessTokenKey = accessTokenKey;
2081
- this.generateToken = memoizePromise(this.generateToken);
2082
- this.refreshToken = memoizePromise(this.refreshToken);
2083
- }
2166
+ _classPrivateFieldGet(this, _history).push(log);
2084
2167
 
2085
- _createClass(TokenStorage, [{
2086
- key: "setAsyncStorage",
2087
- value: function setAsyncStorage(asyncStorage) {
2088
- _classPrivateFieldSet(this, _asyncStorage, asyncStorage);
2089
- }
2090
- }, {
2091
- key: "hasAccessToken",
2092
- value: function hasAccessToken() {
2093
- return _classPrivateFieldGet(this, _asyncStorage).getItem(this.accessTokenKey).then(function (accessToken) {
2094
- return !!accessToken;
2095
- });
2168
+ return log.id;
2096
2169
  }
2097
2170
  }, {
2098
- key: "getAccessToken",
2099
- value: function getAccessToken() {
2100
- return this.getAccessTokenObject().then(function (token) {
2101
- return token && token.access_token;
2171
+ key: "logResponse",
2172
+ value: function logResponse(response, requestId) {
2173
+ var id = requestId || generateId(); // console.log('clone');
2174
+ // const clonedResponse = response.clone(); // THIS IS THE LINE THAT CAUSES THE PROBLEM
2175
+ // console.log('after clone', clonedResponse.status);
2176
+
2177
+ var logContent = {
2178
+ status: response.status,
2179
+ // clonedResponse.status,
2180
+ headers: Object.fromEntries(response.headers)
2181
+ };
2182
+
2183
+ var foundLogIndex = _classPrivateFieldGet(this, _history).findIndex(function (log) {
2184
+ return log.id === id;
2102
2185
  });
2186
+
2187
+ if (foundLogIndex > -1) {
2188
+ _classPrivateFieldGet(this, _history)[foundLogIndex].response = logContent;
2189
+ _classPrivateFieldGet(this, _history)[foundLogIndex].logTimes.response = Date.now();
2190
+ } else {
2191
+ _classPrivateFieldGet(this, _history).push({
2192
+ id: id,
2193
+ response: logContent,
2194
+ logTimes: {
2195
+ response: Date.now()
2196
+ }
2197
+ });
2198
+ }
2199
+
2200
+ return id;
2103
2201
  }
2104
- }, {
2105
- key: "getAccessTokenObject",
2106
- value: function getAccessTokenObject() {
2107
- var _this = this;
2202
+ }]);
2108
2203
 
2109
- return _classPrivateFieldGet(this, _asyncStorage).getItem(this.accessTokenKey).then(function (token) {
2110
- if (token) {
2111
- var tokenObject = JSON.parse(token);
2204
+ return Logger;
2205
+ }();
2112
2206
 
2113
- if (_typeof(tokenObject) !== 'object') {
2114
- return null;
2115
- }
2207
+ var _repositoryList = new WeakMap();
2116
2208
 
2117
- return tokenObject;
2118
- }
2209
+ var RestClientSdk = /*#__PURE__*/function () {
2210
+ function RestClientSdk(tokenStorage, config, mapping) {
2211
+ var serializer = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new JsSerializer();
2119
2212
 
2120
- if (_classPrivateFieldGet(_this, _hasATokenBeenGenerated)) {
2121
- return null;
2122
- }
2213
+ _classCallCheck(this, RestClientSdk);
2123
2214
 
2124
- if (typeof _classPrivateFieldGet(_this, _tokenGenerator).autoGenerateToken === 'function') {
2125
- return _classPrivateFieldGet(_this, _tokenGenerator).autoGenerateToken();
2126
- }
2215
+ _defineProperty(this, "config", void 0);
2127
2216
 
2128
- throw new Error('No token has been generated yet.');
2129
- });
2130
- }
2131
- }, {
2132
- key: "logout",
2133
- value: function logout() {
2134
- return _classPrivateFieldGet(this, _asyncStorage).removeItem(this.accessTokenKey);
2135
- }
2136
- }, {
2137
- key: "_addExpiresAtToResponseData",
2138
- value: function _addExpiresAtToResponseData(responseData, callTimestamp) {
2139
- if (!responseData) {
2140
- return responseData;
2141
- }
2217
+ _defineProperty(this, "tokenStorage", void 0);
2142
2218
 
2143
- var updatedResponseData = _objectSpread2(_objectSpread2({}, responseData), {}, {
2144
- expires_at: null
2145
- });
2219
+ _defineProperty(this, "serializer", void 0);
2146
2220
 
2147
- if (typeof updatedResponseData.expires_in !== 'undefined' && updatedResponseData.expires_in !== null // && updatedResponseData.expires_in >= 0
2148
- ) {
2149
- updatedResponseData.expires_at = Math.round(callTimestamp / 1000) + updatedResponseData.expires_in;
2150
- }
2221
+ _defineProperty(this, "mapping", void 0);
2151
2222
 
2152
- return updatedResponseData;
2153
- }
2154
- }, {
2155
- key: "generateToken",
2156
- value: function generateToken(parameters) {
2157
- var _this2 = this;
2223
+ _defineProperty(this, "unitOfWork", void 0);
2158
2224
 
2159
- var callTimestamp = Date.now();
2160
- return _classPrivateFieldGet(this, _tokenGenerator).generateToken(parameters).then(this.handleTokenResponse).then(function (body) {
2161
- var updatedResponseData = _this2._addExpiresAtToResponseData(body, callTimestamp);
2225
+ _repositoryList.set(this, {
2226
+ writable: true,
2227
+ value: void 0
2228
+ });
2229
+
2230
+ _defineProperty(this, "logger", void 0);
2162
2231
 
2163
- return _this2._storeAccessToken(updatedResponseData).then(function () {
2164
- _classPrivateFieldSet(_this2, _hasATokenBeenGenerated, true);
2232
+ this.checkConfigValidity(config);
2165
2233
 
2166
- return updatedResponseData;
2167
- });
2168
- });
2234
+ if (!(mapping instanceof Mapping)) {
2235
+ throw new TypeError('mapping should be an instance of `Mapping`');
2169
2236
  }
2170
- }, {
2171
- key: "refreshToken",
2172
- value: function refreshToken() {
2173
- var _this3 = this;
2174
2237
 
2175
- return _classPrivateFieldGet(this, _asyncStorage).getItem(this.accessTokenKey).then(function (token) {
2176
- var callTimestamp = Date.now();
2177
- return _classPrivateFieldGet(_this3, _tokenGenerator).refreshToken(token ? JSON.parse(token) : null).then(_this3.handleTokenResponse).then(function (body) {
2178
- var updatedResponseData = _this3._addExpiresAtToResponseData(body, callTimestamp);
2238
+ this.config = this._mergeWithBaseConfig(config);
2239
+ this.tokenStorage = tokenStorage;
2240
+ this.serializer = serializer;
2241
+ this.mapping = mapping;
2242
+ this.unitOfWork = new UnitOfWork(this.mapping, this.config.unitOfWorkEnabled);
2179
2243
 
2180
- return _this3._storeAccessToken(updatedResponseData).then(function () {
2181
- return updatedResponseData;
2182
- });
2183
- });
2184
- });
2244
+ if (config.loggerEnabled) {
2245
+ this.logger = new Logger();
2185
2246
  }
2186
- }, {
2187
- key: "handleTokenResponse",
2188
- value: function handleTokenResponse(responseOrBody) {
2189
- if (isResponse(responseOrBody)) {
2190
- var response = responseOrBody;
2191
- var originalResponse = response.clone();
2192
- return response.json().then(function (body) {
2193
- if (isOauthError(body)) {
2194
- // throw error if response body is an oauth error
2195
- manageOauthError(body, response);
2196
- } else if (response.status >= 400) {
2197
- // throw an error if response status code is an "error" status code
2198
- throw getHttpErrorFromResponse(originalResponse);
2199
- }
2200
2247
 
2201
- return body;
2202
- })["catch"](function (err) {
2203
- if (!(err instanceof OauthError)) {
2204
- throw new OauthError(err.type, getHttpErrorFromResponse(originalResponse));
2205
- }
2248
+ _classPrivateFieldSet(this, _repositoryList, {});
2249
+ }
2250
+ /**
2251
+ * get a repository by it's metadata "key" attribute
2252
+ *
2253
+ * @param {string} key the repository "key" (the first argument of `new ClassMetadata`)
2254
+ */
2206
2255
 
2207
- throw err;
2208
- });
2209
- }
2210
2256
 
2211
- var body = responseOrBody;
2257
+ _createClass(RestClientSdk, [{
2258
+ key: "getRepository",
2259
+ value: function getRepository(key) {
2260
+ if (!_classPrivateFieldGet(this, _repositoryList)[key]) {
2261
+ var metadata = this.mapping.getClassMetadataByKey(key);
2212
2262
 
2213
- if (isOauthError(body)) {
2214
- // throw error if response body is an oauth error
2215
- manageOauthError(body);
2216
- }
2263
+ if (!metadata) {
2264
+ throw new Error("Unable to get metadata for repository ".concat(key));
2265
+ } // eslint-disable-next-line new-cap
2217
2266
 
2218
- return Promise.resolve(body);
2219
- }
2220
- /**
2221
- * Return the number of second when the token will expire
2222
- * return value can be negative if the token is already expired
2223
- */
2224
2267
 
2225
- }, {
2226
- key: "getCurrentTokenExpiresIn",
2227
- value: function getCurrentTokenExpiresIn() {
2228
- return this.getAccessTokenObject().then(function (accessTokenObject) {
2229
- if (accessTokenObject === null) {
2230
- throw new Error('No token has been stored.');
2231
- }
2268
+ _classPrivateFieldGet(this, _repositoryList)[key] = generateRepository(this, metadata, this.config.unitOfWorkEnabled);
2269
+ } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2232
2270
 
2233
- if (typeof accessTokenObject.expires_at === 'undefined' || accessTokenObject.expires_at === null) {
2234
- return null;
2235
- }
2236
2271
 
2237
- var now = Math.round(Date.now() / 1000);
2238
- return accessTokenObject.expires_at - now;
2239
- });
2272
+ return _classPrivateFieldGet(this, _repositoryList)[key];
2240
2273
  }
2241
2274
  }, {
2242
- key: "_storeAccessToken",
2243
- value: function _storeAccessToken(responseData) {
2244
- return _classPrivateFieldGet(this, _asyncStorage).setItem(this.accessTokenKey, JSON.stringify(responseData));
2275
+ key: "_mergeWithBaseConfig",
2276
+ value: function _mergeWithBaseConfig(config) {
2277
+ var newConfig = config;
2278
+ newConfig.useDefaultParameters = config.useDefaultParameters === undefined ? true : config.useDefaultParameters;
2279
+ newConfig.authorizationType = config.authorizationType || 'Bearer';
2280
+ return newConfig;
2281
+ }
2282
+ }, {
2283
+ key: "checkConfigValidity",
2284
+ value: function checkConfigValidity(config) {
2285
+ if (!(config && config.path && config.scheme)) {
2286
+ throw new RangeError("SDK config is not valid, it should contain a \"path\", a \"scheme\" parameter,\n and may contain a \"port\" and a \"useDefaultParameters\" parameter");
2287
+ }
2245
2288
  }
2246
2289
  }]);
2247
2290
 
2248
- return TokenStorage;
2291
+ return RestClientSdk;
2249
2292
  }();
2250
2293
 
2251
2294
  var AbstractTokenGenerator = /*#__PURE__*/function () {
2252
- function AbstractTokenGenerator(tokenGeneratorConfig) {
2295
+ function AbstractTokenGenerator(tokenGeneratorConfig, logger) {
2253
2296
  _classCallCheck(this, AbstractTokenGenerator);
2254
2297
 
2255
2298
  _defineProperty(this, "tokenGeneratorConfig", void 0);
2256
2299
 
2300
+ _defineProperty(this, "logger", void 0);
2301
+
2302
+ if (logger) {
2303
+ this.logger = logger;
2304
+ }
2305
+
2257
2306
  this.tokenGeneratorConfig = tokenGeneratorConfig;
2258
2307
 
2259
2308
  if (typeof this.checkTokenGeneratorConfig === 'function') {
@@ -2326,7 +2375,7 @@
2326
2375
  this._checkGenerateParameters(parameters);
2327
2376
 
2328
2377
  var url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
2329
- return fetch(url, {
2378
+ var params = {
2330
2379
  method: 'POST',
2331
2380
  headers: {
2332
2381
  'Content-Type': 'application/x-www-form-urlencoded'
@@ -2338,8 +2387,16 @@
2338
2387
  // TODO : secure this ?
2339
2388
  redirect_uri: this.tokenGeneratorConfig.redirectUri,
2340
2389
  code: parameters.code
2341
- })
2342
- });
2390
+ }).toString()
2391
+ };
2392
+
2393
+ if (this.logger) {
2394
+ this.logger.logRequest(_objectSpread2({
2395
+ url: url
2396
+ }, params));
2397
+ }
2398
+
2399
+ return fetch(url, params);
2343
2400
  }
2344
2401
  /**
2345
2402
  * This function needs to refresh the current possibly expired access token
@@ -2358,7 +2415,7 @@
2358
2415
  }
2359
2416
 
2360
2417
  var url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
2361
- return fetch(url, {
2418
+ var params = {
2362
2419
  method: 'POST',
2363
2420
  headers: {
2364
2421
  'Content-Type': 'application/x-www-form-urlencoded'
@@ -2368,8 +2425,16 @@
2368
2425
  client_id: this.tokenGeneratorConfig.clientId,
2369
2426
  client_secret: this.tokenGeneratorConfig.clientSecret,
2370
2427
  refresh_token: oldAccessToken.refresh_token
2371
- })
2372
- });
2428
+ }).toString()
2429
+ };
2430
+
2431
+ if (this.logger) {
2432
+ this.logger.logRequest(_objectSpread2({
2433
+ url: url
2434
+ }, params));
2435
+ }
2436
+
2437
+ return fetch(url, params);
2373
2438
  }
2374
2439
  }, {
2375
2440
  key: "checkTokenGeneratorConfig",
@@ -2406,6 +2471,46 @@
2406
2471
  return AuthorizationCodeFlowTokenGenerator;
2407
2472
  }(AbstractTokenGenerator);
2408
2473
 
2474
+ /* eslint-disable import/prefer-default-export */
2475
+ // memoize promise returning function so that it returns
2476
+ // the same promise if called again before resolve / reject
2477
+ function memoizePromise(callback) {
2478
+ var cache = {};
2479
+
2480
+ function memoized() {
2481
+ for (var _len = arguments.length, parameters = new Array(_len), _key = 0; _key < _len; _key++) {
2482
+ parameters[_key] = arguments[_key];
2483
+ }
2484
+
2485
+ var cacheKey = JSON.stringify(parameters);
2486
+ var cacheValue = cache[cacheKey];
2487
+
2488
+ if (cacheValue) {
2489
+ return cacheValue;
2490
+ } // Get and add the value to the cache
2491
+
2492
+
2493
+ var value = callback.apply(this, parameters);
2494
+ cache[cacheKey] = value;
2495
+
2496
+ if (!value || typeof value.then !== 'function') {
2497
+ throw new Error('Memoization Error, Async function returned non-promise value');
2498
+ } // Delete the value regardless of whether it resolves or rejects
2499
+
2500
+
2501
+ return value.then(function (internalValue) {
2502
+ cache[cacheKey] = false;
2503
+ return internalValue;
2504
+ }, function (err) {
2505
+ cache[cacheKey] = false;
2506
+ throw err;
2507
+ });
2508
+ }
2509
+
2510
+ memoized.cache = cache;
2511
+ return memoized;
2512
+ }
2513
+
2409
2514
  var ERROR_CONFIG_EMPTY = 'TokenGenerator config must be set';
2410
2515
  var ERROR_CONFIG_PATH_SCHEME = 'TokenGenerator config is not valid, it should contain a "path", a "scheme" parameter';
2411
2516
  var ERROR_CONFIG_CLIENT_INFORMATIONS = 'TokenGenerator config is not valid, it should contain a "clientId", a "clientSecret" parameter';
@@ -2441,14 +2546,22 @@
2441
2546
  body.append('scope', this.tokenGeneratorConfig.scope);
2442
2547
  }
2443
2548
 
2444
- var url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
2445
- return fetch(url, {
2549
+ var params = {
2446
2550
  method: 'POST',
2447
2551
  headers: {
2448
2552
  'Content-Type': 'application/x-www-form-urlencoded'
2449
2553
  },
2450
- body: body
2451
- });
2554
+ body: body.toString()
2555
+ };
2556
+ var url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
2557
+
2558
+ if (this.logger) {
2559
+ this.logger.logRequest(_objectSpread2({
2560
+ url: url
2561
+ }, params));
2562
+ }
2563
+
2564
+ return fetch(url, params);
2452
2565
  }
2453
2566
  }, {
2454
2567
  key: "refreshToken",
@@ -2513,13 +2626,21 @@
2513
2626
  }
2514
2627
 
2515
2628
  var url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
2516
- return fetch(url, {
2629
+ var params = {
2517
2630
  method: 'POST',
2518
2631
  headers: {
2519
2632
  'Content-Type': 'application/x-www-form-urlencoded'
2520
2633
  },
2521
- body: body
2522
- });
2634
+ body: body.toString()
2635
+ };
2636
+
2637
+ if (this.logger) {
2638
+ this.logger.logRequest(_objectSpread2({
2639
+ url: url
2640
+ }, params));
2641
+ }
2642
+
2643
+ return fetch(url, params);
2523
2644
  }
2524
2645
  }, {
2525
2646
  key: "refreshToken",
@@ -2542,13 +2663,21 @@
2542
2663
  }
2543
2664
 
2544
2665
  var url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
2545
- return fetch(url, {
2666
+ var params = {
2546
2667
  method: 'POST',
2547
2668
  headers: {
2548
2669
  'Content-Type': 'application/x-www-form-urlencoded'
2549
2670
  },
2550
- body: body
2551
- });
2671
+ body: body.toString()
2672
+ };
2673
+
2674
+ if (this.logger) {
2675
+ this.logger.logRequest(_objectSpread2({
2676
+ url: url
2677
+ }, params));
2678
+ }
2679
+
2680
+ return fetch(url, params);
2552
2681
  }
2553
2682
  }, {
2554
2683
  key: "checkTokenGeneratorConfig",
@@ -2643,254 +2772,252 @@
2643
2772
  return ProvidedTokenGenerator;
2644
2773
  }();
2645
2774
 
2646
- var Attribute =
2647
- /**
2648
- * @param {string} serializedKey the key returned from your API
2649
- * @param {null|string} attributeName the name in your entity, default to the `serializedKey` attribute
2650
- * @param {string} type type of the attribute
2651
- * @param {boolean} isIdentifier is this attribute the entity identifier
2652
- */
2653
- function Attribute(serializedKey) {
2654
- var attributeName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
2655
- var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'string';
2656
- var isIdentifier = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
2657
-
2658
- _classCallCheck(this, Attribute);
2659
-
2660
- _defineProperty(this, "serializedKey", void 0);
2661
-
2662
- _defineProperty(this, "attributeName", void 0);
2663
-
2664
- _defineProperty(this, "type", void 0);
2775
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2776
+ function isResponse(response) {
2777
+ return typeof (response === null || response === void 0 ? void 0 : response.json) === 'function';
2778
+ }
2665
2779
 
2666
- _defineProperty(this, "isIdentifier", void 0);
2780
+ function manageOauthError(body, response) {
2781
+ var error;
2667
2782
 
2668
- if (!serializedKey) {
2669
- throw new TypeError('`serializedKey` must not be empty');
2783
+ if (response) {
2784
+ error = getHttpErrorFromResponse(response);
2670
2785
  }
2671
2786
 
2672
- this.serializedKey = serializedKey;
2673
- this.attributeName = attributeName || this.serializedKey;
2674
- this.type = type;
2675
- this.isIdentifier = isIdentifier;
2676
- };
2787
+ if (body.error === 'invalid_grant') {
2788
+ throw new InvalidGrantError(body.error, error);
2789
+ }
2677
2790
 
2678
- var _attributeList = new WeakMap();
2791
+ if (body.error === 'invalid_scope') {
2792
+ throw new InvalidScopeError(body.error, error);
2793
+ }
2679
2794
 
2680
- var _relationList = new WeakMap();
2795
+ throw new OauthError(body.error, error);
2796
+ }
2681
2797
 
2682
- var _identifierAttribute = new WeakMap();
2798
+ var _tokenGenerator = new WeakMap();
2683
2799
 
2684
- var ClassMetadata = /*#__PURE__*/function () {
2685
- /**
2686
- * @param {string} key mandatory, will be passed in your serializer
2687
- * @param {string|null} pathRoot the endpoint of your API: will be added to the mapping prefix ('/v1' here)
2688
- * @param {typeof AbstractClient} repositoryClass [Overriding repository]{@link https://github.com/mapado/rest-client-js-sdk#overriding-repository} for more detail
2689
- */
2690
- function ClassMetadata(key) {
2691
- var pathRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
2692
- var repositoryClass = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : AbstractClient;
2800
+ var _hasATokenBeenGenerated = new WeakMap();
2693
2801
 
2694
- _classCallCheck(this, ClassMetadata);
2802
+ var _asyncStorage = new WeakMap();
2695
2803
 
2696
- _defineProperty(this, "key", void 0);
2804
+ var _logger = new WeakMap();
2697
2805
 
2698
- _defineProperty(this, "pathRoot", void 0);
2806
+ var TokenStorage = /*#__PURE__*/function () {
2807
+ function TokenStorage(tokenGenerator, asyncStorage) {
2808
+ var accessTokenKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'rest_client_sdk.api.access_token';
2809
+ var logger = arguments.length > 3 ? arguments[3] : undefined;
2699
2810
 
2700
- _defineProperty(this, "repositoryClass", void 0);
2811
+ _classCallCheck(this, TokenStorage);
2701
2812
 
2702
- _attributeList.set(this, {
2813
+ _tokenGenerator.set(this, {
2703
2814
  writable: true,
2704
2815
  value: void 0
2705
2816
  });
2706
2817
 
2707
- _relationList.set(this, {
2818
+ _hasATokenBeenGenerated.set(this, {
2708
2819
  writable: true,
2709
2820
  value: void 0
2710
2821
  });
2711
2822
 
2712
- _identifierAttribute.set(this, {
2823
+ _defineProperty(this, "accessTokenKey", void 0);
2824
+
2825
+ _asyncStorage.set(this, {
2713
2826
  writable: true,
2714
2827
  value: void 0
2715
2828
  });
2716
2829
 
2717
- if (!key) {
2718
- throw new TypeError('key attribute are required');
2719
- }
2830
+ _logger.set(this, {
2831
+ writable: true,
2832
+ value: void 0
2833
+ });
2720
2834
 
2721
- this.key = key;
2722
- this.pathRoot = pathRoot || key; // this.modelName = modelName;
2835
+ if (logger) {
2836
+ _classPrivateFieldSet(this, _logger, logger);
2837
+ }
2723
2838
 
2724
- this.repositoryClass = repositoryClass;
2839
+ _classPrivateFieldSet(this, _tokenGenerator, tokenGenerator);
2725
2840
 
2726
- _classPrivateFieldSet(this, _attributeList, {});
2841
+ _classPrivateFieldSet(this, _hasATokenBeenGenerated, false);
2727
2842
 
2728
- _classPrivateFieldSet(this, _relationList, {});
2843
+ this.setAsyncStorage(asyncStorage);
2844
+ this.accessTokenKey = accessTokenKey;
2845
+ this.handleTokenResponse = this.handleTokenResponse.bind(this);
2846
+ this.generateToken = memoizePromise(this.generateToken);
2847
+ this.refreshToken = memoizePromise(this.refreshToken);
2729
2848
  }
2730
2849
 
2731
- _createClass(ClassMetadata, [{
2732
- key: "getAttribute",
2733
- value: function getAttribute(name) {
2734
- return _classPrivateFieldGet(this, _attributeList)[name];
2735
- }
2736
- }, {
2737
- key: "hasIdentifierAttribute",
2738
- value: function hasIdentifierAttribute() {
2739
- return !!_classPrivateFieldGet(this, _identifierAttribute);
2850
+ _createClass(TokenStorage, [{
2851
+ key: "setAsyncStorage",
2852
+ value: function setAsyncStorage(asyncStorage) {
2853
+ _classPrivateFieldSet(this, _asyncStorage, asyncStorage);
2740
2854
  }
2741
2855
  }, {
2742
- key: "getIdentifierAttribute",
2743
- value: function getIdentifierAttribute() {
2744
- if (!_classPrivateFieldGet(this, _identifierAttribute)) {
2745
- throw new TypeError("\"".concat(this.key, "\" has no identifier attribute set. Did you call \"setAttributeList\" first ?"));
2746
- }
2747
-
2748
- return _classPrivateFieldGet(this, _identifierAttribute);
2856
+ key: "hasAccessToken",
2857
+ value: function hasAccessToken() {
2858
+ return _classPrivateFieldGet(this, _asyncStorage).getItem(this.accessTokenKey).then(function (accessToken) {
2859
+ return !!accessToken;
2860
+ });
2749
2861
  }
2750
2862
  }, {
2751
- key: "getAttributeList",
2752
- value: function getAttributeList() {
2753
- return _classPrivateFieldGet(this, _attributeList);
2863
+ key: "getAccessToken",
2864
+ value: function getAccessToken() {
2865
+ return this.getAccessTokenObject().then(function (token) {
2866
+ return token && token.access_token;
2867
+ });
2754
2868
  }
2755
2869
  }, {
2756
- key: "setAttributeList",
2757
- value: function setAttributeList(attributeList) {
2870
+ key: "getAccessTokenObject",
2871
+ value: function getAccessTokenObject() {
2758
2872
  var _this = this;
2759
2873
 
2760
- _classPrivateFieldSet(this, _attributeList, {});
2761
-
2762
- _classPrivateFieldSet(this, _identifierAttribute, undefined);
2874
+ return _classPrivateFieldGet(this, _asyncStorage).getItem(this.accessTokenKey).then(function (token) {
2875
+ if (token) {
2876
+ var tokenObject = JSON.parse(token);
2763
2877
 
2764
- attributeList.forEach(function (attribute) {
2765
- _classPrivateFieldGet(_this, _attributeList)[attribute.serializedKey] = attribute;
2878
+ if (_typeof(tokenObject) !== 'object') {
2879
+ return null;
2880
+ }
2766
2881
 
2767
- if (attribute.isIdentifier) {
2768
- _classPrivateFieldSet(_this, _identifierAttribute, attribute);
2882
+ return tokenObject;
2769
2883
  }
2770
- });
2771
2884
 
2772
- if (!_classPrivateFieldGet(this, _identifierAttribute)) {
2773
- throw new TypeError("\"".concat(this.key, "\" has no identifier attribute set. You must set all your attributes in one time and send an attribute with \"isIdentifier=true\""));
2774
- }
2775
- }
2776
- }, {
2777
- key: "setRelationList",
2778
- value: function setRelationList(relationList) {
2779
- var _this2 = this;
2885
+ if (_classPrivateFieldGet(_this, _hasATokenBeenGenerated)) {
2886
+ return null;
2887
+ }
2780
2888
 
2781
- _classPrivateFieldSet(this, _relationList, {});
2889
+ if (typeof _classPrivateFieldGet(_this, _tokenGenerator).autoGenerateToken === 'function') {
2890
+ return _classPrivateFieldGet(_this, _tokenGenerator).autoGenerateToken();
2891
+ }
2782
2892
 
2783
- relationList.forEach(function (relation) {
2784
- _classPrivateFieldGet(_this2, _relationList)[relation.serializedKey] = relation;
2785
- _classPrivateFieldGet(_this2, _attributeList)[relation.serializedKey] = new Attribute(relation.serializedKey, relation.serializedKey, relation.isRelationToMany() ? 'array' : 'object');
2893
+ throw new Error('No token has been generated yet.');
2786
2894
  });
2787
2895
  }
2788
2896
  }, {
2789
- key: "getRelation",
2790
- value: function getRelation(key) {
2791
- return _classPrivateFieldGet(this, _relationList)[key];
2897
+ key: "logout",
2898
+ value: function logout() {
2899
+ return _classPrivateFieldGet(this, _asyncStorage).removeItem(this.accessTokenKey);
2792
2900
  }
2793
2901
  }, {
2794
- key: "getDefaultSerializedModel",
2795
- value: function getDefaultSerializedModel() {
2796
- var _this3 = this;
2902
+ key: "_addExpiresAtToResponseData",
2903
+ value: function _addExpiresAtToResponseData(responseData, callTimestamp) {
2904
+ if (!responseData) {
2905
+ return responseData;
2906
+ }
2797
2907
 
2798
- var out = {};
2799
- Object.keys(_classPrivateFieldGet(this, _attributeList)).forEach(function (serializedKey) {
2800
- out[serializedKey] = null;
2908
+ var updatedResponseData = _objectSpread2(_objectSpread2({}, responseData), {}, {
2909
+ expires_at: null
2801
2910
  });
2802
- Object.keys(_classPrivateFieldGet(this, _relationList)).forEach(function (serializedKey) {
2803
- var relation = _classPrivateFieldGet(_this3, _relationList)[serializedKey];
2804
2911
 
2805
- if (relation.isRelationToMany()) {
2806
- out[serializedKey] = [];
2912
+ if (typeof updatedResponseData.expires_in !== 'undefined' && updatedResponseData.expires_in !== null // && updatedResponseData.expires_in >= 0
2913
+ ) {
2914
+ updatedResponseData.expires_at = Math.round(callTimestamp / 1000) + updatedResponseData.expires_in;
2807
2915
  }
2808
- });
2809
- return out;
2916
+
2917
+ return updatedResponseData;
2810
2918
  }
2811
- }]);
2919
+ }, {
2920
+ key: "generateToken",
2921
+ value: function generateToken(parameters) {
2922
+ var _this2 = this;
2812
2923
 
2813
- return ClassMetadata;
2814
- }();
2924
+ var callTimestamp = Date.now();
2925
+ return _classPrivateFieldGet(this, _tokenGenerator).generateToken(parameters).then(this.handleTokenResponse).then(function (body) {
2926
+ var updatedResponseData = _this2._addExpiresAtToResponseData(body, callTimestamp);
2815
2927
 
2816
- var RelationTypes;
2928
+ return _this2._storeAccessToken(updatedResponseData).then(function () {
2929
+ _classPrivateFieldSet(_this2, _hasATokenBeenGenerated, true);
2817
2930
 
2818
- (function (RelationTypes) {
2819
- RelationTypes["ONE_TO_ONE"] = "ONE_TO_ONE";
2820
- RelationTypes["ONE_TO_MANY"] = "ONE_TO_MANY";
2821
- RelationTypes["MANY_TO_MANY"] = "MANY_TO_MANY";
2822
- RelationTypes["MANY_TO_ONE"] = "MANY_TO_ONE";
2823
- })(RelationTypes || (RelationTypes = {}));
2931
+ return updatedResponseData;
2932
+ });
2933
+ });
2934
+ }
2935
+ }, {
2936
+ key: "refreshToken",
2937
+ value: function refreshToken() {
2938
+ var _this3 = this;
2824
2939
 
2825
- var Relation = /*#__PURE__*/function () {
2826
- /**
2827
- * @param {RelationTypes} type the type of relation
2828
- * @param {string} targetMetadataKey must match the first argument of `ClassMetadata` constructor of the target entity
2829
- * @param {string} serializedKey the key returned from your API
2830
- * @param {string|null} attributeName the name in your entity, default to the `serializedKey` attribute
2831
- */
2832
- function Relation(type, targetMetadataKey, serializedKey) {
2833
- var attributeName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
2940
+ return _classPrivateFieldGet(this, _asyncStorage).getItem(this.accessTokenKey).then(function (token) {
2941
+ var callTimestamp = Date.now();
2942
+ return _classPrivateFieldGet(_this3, _tokenGenerator).refreshToken(token ? JSON.parse(token) : null).then(_this3.handleTokenResponse).then(function (body) {
2943
+ var updatedResponseData = _this3._addExpiresAtToResponseData(body, callTimestamp);
2834
2944
 
2835
- _classCallCheck(this, Relation);
2945
+ return _this3._storeAccessToken(updatedResponseData).then(function () {
2946
+ return updatedResponseData;
2947
+ });
2948
+ });
2949
+ });
2950
+ }
2951
+ }, {
2952
+ key: "handleTokenResponse",
2953
+ value: function handleTokenResponse(responseOrBody) {
2954
+ if (isResponse(responseOrBody)) {
2955
+ var response = responseOrBody;
2956
+ var originalResponse = response.clone();
2836
2957
 
2837
- _defineProperty(this, "type", void 0);
2958
+ if (_classPrivateFieldGet(this, _logger)) {
2959
+ _classPrivateFieldGet(this, _logger).logResponse(response);
2960
+ }
2838
2961
 
2839
- _defineProperty(this, "targetMetadataKey", void 0);
2962
+ return response.json().then(function (body) {
2963
+ if (isOauthError(body)) {
2964
+ // throw error if response body is an oauth error
2965
+ manageOauthError(body, response);
2966
+ } else if (response.status >= 400) {
2967
+ // throw an error if response status code is an "error" status code
2968
+ throw getHttpErrorFromResponse(originalResponse);
2969
+ }
2840
2970
 
2841
- _defineProperty(this, "serializedKey", void 0);
2971
+ return body;
2972
+ })["catch"](function (err) {
2973
+ if (!(err instanceof OauthError)) {
2974
+ throw new OauthError(err.type, getHttpErrorFromResponse(originalResponse));
2975
+ }
2842
2976
 
2843
- _defineProperty(this, "attributeName", void 0);
2977
+ throw err;
2978
+ });
2979
+ }
2844
2980
 
2845
- this.type = type;
2846
- this.targetMetadataKey = targetMetadataKey;
2847
- this.serializedKey = serializedKey;
2848
- this.attributeName = attributeName || this.serializedKey;
2849
- }
2981
+ var body = responseOrBody;
2850
2982
 
2851
- _createClass(Relation, [{
2852
- key: "isOneToOne",
2853
- value: function isOneToOne() {
2854
- return this.type === Relation.ONE_TO_ONE;
2855
- }
2856
- }, {
2857
- key: "isOneToMany",
2858
- value: function isOneToMany() {
2859
- return this.type === Relation.ONE_TO_MANY;
2860
- }
2861
- }, {
2862
- key: "isManyToOne",
2863
- value: function isManyToOne() {
2864
- return this.type === Relation.MANY_TO_ONE;
2865
- }
2866
- }, {
2867
- key: "isManyToMany",
2868
- value: function isManyToMany() {
2869
- return this.type === Relation.MANY_TO_MANY;
2983
+ if (isOauthError(body)) {
2984
+ // throw error if response body is an oauth error
2985
+ manageOauthError(body);
2986
+ }
2987
+
2988
+ return Promise.resolve(body);
2870
2989
  }
2990
+ /**
2991
+ * Return the number of second when the token will expire
2992
+ * return value can be negative if the token is already expired
2993
+ */
2994
+
2871
2995
  }, {
2872
- key: "isRelationToMany",
2873
- value: function isRelationToMany() {
2874
- return this.isManyToMany() || this.isOneToMany();
2996
+ key: "getCurrentTokenExpiresIn",
2997
+ value: function getCurrentTokenExpiresIn() {
2998
+ return this.getAccessTokenObject().then(function (accessTokenObject) {
2999
+ if (accessTokenObject === null) {
3000
+ throw new Error('No token has been stored.');
3001
+ }
3002
+
3003
+ if (typeof accessTokenObject.expires_at === 'undefined' || accessTokenObject.expires_at === null) {
3004
+ return null;
3005
+ }
3006
+
3007
+ var now = Math.round(Date.now() / 1000);
3008
+ return accessTokenObject.expires_at - now;
3009
+ });
2875
3010
  }
2876
3011
  }, {
2877
- key: "isRelationToOne",
2878
- value: function isRelationToOne() {
2879
- return this.isManyToOne() || this.isOneToOne();
3012
+ key: "_storeAccessToken",
3013
+ value: function _storeAccessToken(responseData) {
3014
+ return _classPrivateFieldGet(this, _asyncStorage).setItem(this.accessTokenKey, JSON.stringify(responseData));
2880
3015
  }
2881
3016
  }]);
2882
3017
 
2883
- return Relation;
3018
+ return TokenStorage;
2884
3019
  }();
2885
3020
 
2886
- _defineProperty(Relation, "ONE_TO_ONE", RelationTypes.ONE_TO_ONE);
2887
-
2888
- _defineProperty(Relation, "ONE_TO_MANY", RelationTypes.ONE_TO_MANY);
2889
-
2890
- _defineProperty(Relation, "MANY_TO_ONE", RelationTypes.MANY_TO_ONE);
2891
-
2892
- _defineProperty(Relation, "MANY_TO_MANY", RelationTypes.MANY_TO_MANY);
2893
-
2894
3021
  exports.AbstractClient = AbstractClient;
2895
3022
  exports.AbstractTokenGenerator = AbstractTokenGenerator;
2896
3023
  exports.Attribute = Attribute;
@@ -2904,6 +3031,7 @@
2904
3031
  exports.InternalServerError = InternalServerError;
2905
3032
  exports.InvalidGrantError = InvalidGrantError;
2906
3033
  exports.InvalidScopeError = InvalidScopeError;
3034
+ exports.Logger = Logger;
2907
3035
  exports.Mapping = Mapping;
2908
3036
  exports.OauthError = OauthError;
2909
3037
  exports.PasswordGenerator = PasswordGenerator;