rest-client-sdk 7.0.0-rc.7 → 7.0.0-rc.9

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