Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

rest-client-sdk

Package Overview
Dependencies
Maintainers
3
Versions
109
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rest-client-sdk - npm Package Compare versions

Comparing version 2.0.1 to 2.1.0

26

CHANGELOG.md

@@ -5,8 +5,16 @@ # Changelog

## 2.1.0
### Changed
* Add method getAccessTokenObject to TokenStorage
## 2.0.1
### Changed
* Better packaging system [#48](https://github.com/mapado/rest-client-js-sdk/pull/48)
* Better packaging system [#48](https://github.com/mapado/rest-client-js-sdk/pull/48)
## 2.0.0
### Added

@@ -29,3 +37,2 @@

```js

@@ -56,2 +63,3 @@ class SomeClient extends AbstractClient {

```
* [Breaking] Custom Serializer: If you had a Collection entity containing the result of you entities, you will need to implement the [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) on this object, this way, we can register all entities in the unit of work.

@@ -68,32 +76,43 @@

## 2.0.0-rc.14
Check relations in `isValidMapping`
## 2.0.0-rc.13
Fix issue when setting a ManyToOne relatossue when setting a ManyToOne relation to `null`n to `null`
## 2.0.0-rc.12
add a function to test mapping validity
## 2.0.0-rc.10 + 2.0.0-rc.11
deserialize + normalize item in unitofwork
## 2.0.0-rc.9
creating or updating an "complex" entity (not a basic JS object) would throw an error
## 2.0.0-rc.8
remove `async` method (that already returned a Promise object)
## 2.0.0-rc.7
Fix issue when posting a ManyToOne relation with only the id as string
## 2.0.0-rc.6
Fix bug in delete call (not returning the response)
## 2.0.0-rc.5
Fix bug in serializer
## 2.0.0-rc.4
Fix issue with list denormalized oo objects
## 2.0.0-rc.3
Cleaner relations, matches the Arguments attributes

@@ -104,4 +123,5 @@

### Changed
* `ONE_TO_MANY` and `MANY_TO_ONE` constant are now exported via the `Relation.ONE_TO_MANY` and `Relation.MANY_TO_ONE`, not in the main package
* `ONE_TO_MANY` and `MANY_TO_ONE` constant are now exported via the `Relation.ONE_TO_MANY` and `Relation.MANY_TO_ONE`, not in the main package
## 2.0.0-rc.1

@@ -108,0 +128,0 @@

59

dist/index.es.js

@@ -10,12 +10,2 @@ import diff from 'deep-diff';

var classCallCheck = function (instance, Constructor) {

@@ -45,6 +35,2 @@ if (!(instance instanceof Constructor)) {

var defineProperty = function (obj, key, value) {

@@ -65,4 +51,2 @@ if (key in obj) {

var inherits = function (subClass, superClass) {

@@ -84,12 +68,2 @@ if (typeof superClass !== "function" && superClass !== null) {

var possibleConstructorReturn = function (self, call) {

@@ -103,6 +77,2 @@ if (!self) {

var slicedToArray = function () {

@@ -283,2 +253,3 @@ function sliceIterator(arr, i) {

/* eslint no-unused-vars: 0 */
var JsSerializer = function (_Serializer) {

@@ -329,10 +300,2 @@ inherits(JsSerializer, _Serializer);

function isRecord(maybeRecord) {

@@ -342,8 +305,3 @@ return !!(maybeRecord && maybeRecord[IS_RECORD_SENTINEL]);

var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
var IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@';

@@ -1230,2 +1188,9 @@

value: function getAccessToken() {
return this.getAccessTokenObject().then(function (token) {
return token && token.access_token;
});
}
}, {
key: 'getAccessTokenObject',
value: function getAccessTokenObject() {
var _this = this;

@@ -1240,9 +1205,7 @@

if (!_this._hasATokenBeenGenerated && _this._tokenGenerator.canAutogenerateToken) {
return _this.generateToken().then(function (generatedToken) {
return generatedToken && generatedToken.access_token;
});
return _this.generateToken();
}
}
return token && JSON.parse(token).access_token;
return token && JSON.parse(token);
});

@@ -1741,4 +1704,4 @@ }

export default RestClientSdk;
export { AbstractClient, AbstractTokenGenerator, ClientCredentialsGenerator, PasswordGenerator, ProvidedTokenGenerator, Serializer, TokenStorage, AccessDeniedError, BadRequestError, ForbiddenError, HttpError, InternalServerError, ResourceNotFoundError, Mapping, ClassMetadata, Attribute, Relation };
export default RestClientSdk;
//# sourceMappingURL=index.es.js.map
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('deep-diff'), require('urijs')) :
typeof define === 'function' && define.amd ? define(['exports', 'deep-diff', 'urijs'], factory) :
(factory((global['rest-client-sdk'] = {}),global.diff,global.URI));
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('deep-diff'), require('urijs')) :
typeof define === 'function' && define.amd ? define(['exports', 'deep-diff', 'urijs'], factory) :
(factory((global['rest-client-sdk'] = {}),global.diff,global.URI));
}(this, (function (exports,diff,URI) { 'use strict';
diff = diff && diff.hasOwnProperty('default') ? diff['default'] : diff;
URI = URI && URI.hasOwnProperty('default') ? URI['default'] : URI;
diff = diff && diff.hasOwnProperty('default') ? diff['default'] : diff;
URI = URI && URI.hasOwnProperty('default') ? URI['default'] : URI;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
var defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
obj[key] = value;
}
return obj;
};
}();
/* eslint no-unused-vars: 0 */
var Serializer = function () {
function Serializer() {
classCallCheck(this, Serializer);
}
createClass(Serializer, [{
key: 'normalizeItem',
/**
* convert an entity to a plain javascript object
* @param {any} entity - The entity to convert
* @param {ClassMetadata} classMetadata - the class metadata
* @return {object} the object to serialize
*/
value: function normalizeItem(entity, classMetadata) {
return entity;
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
/**
* convert a plain javascript object to string
* @param {object} object - The object to convert to convert
* @param {ClassMetadata} classMetadata - the class metadata
* @return {string} the content of the request
*/
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
}, {
key: 'encodeItem',
value: function encodeItem(object, classMetadata) {
throw new TypeError('`encodeItem` method must be implemented');
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
/**
* convert an entity to string that will be sent as the request content
* @param {any} entity - The entity to convert
* @param {ClassMetadata} classMetadata - the class metadata
* @return {string} the content of the request
*/
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
}, {
key: 'serializeItem',
value: function serializeItem(object, classMetadata) {
var noralizedData = this.normalizeItem(object, classMetadata);
return this.encodeItem(noralizedData, classMetadata);
}
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
/**
* convert a plain object to an entity
* @param {string} object - The plain javascript object
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {any} an entity
*/
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
}, {
key: 'denormalizeItem',
value: function denormalizeItem(object, classMetadata, response) {
return object;
}
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
/**
* convert a string containing an object to a plain javascript object
* @param {string} rawData - The string fetched from the response
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {object} the normalized object
*/
}, {
key: 'decodeItem',
value: function decodeItem(rawData, classMetadata, response) {
throw new TypeError('`decodeItem` method must be implemented');
return _arr;
}
/**
* convert a string containing an object to an entity
* @param {string} rawData - The string fetched from the response
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {object} the entity
*/
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
}, {
key: 'deserializeItem',
value: function deserializeItem(rawData, classMetadata, response) {
var object = this.decodeItem(rawData, classMetadata, response);
return this.denormalizeItem(object, classMetadata, response);
}
/* eslint no-unused-vars: 0 */
/**
* convert a plain object list to an entity list
* @param {array} objectList - The plain javascript object list
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {any} a list of entities
*/
}, {
key: 'denormalizeList',
value: function denormalizeList(objectList, classMetadata, response) {
return objectList;
var Serializer = function () {
function Serializer() {
classCallCheck(this, Serializer);
}
/**
* convert a string containing a list of objects to a list of plain javascript objects
* @param {string} rawListData - The string fetched from the response
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {any} a list of normalized objects
*/
createClass(Serializer, [{
key: 'normalizeItem',
}, {
key: 'decodeList',
value: function decodeList(rawListData, classMetadata, response) {
throw new TypeError('`deserializeList` method must be implemented');
}
/**
* convert an entity to a plain javascript object
* @param {any} entity - The entity to convert
* @param {ClassMetadata} classMetadata - the class metadata
* @return {object} the object to serialize
*/
value: function normalizeItem(entity, classMetadata) {
return entity;
}
/**
* convert a string containing a list of objects to a list of entities
* @param {string} rawListData - The string fetched from the response
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {any} a list of entities
*/
/**
* convert a plain javascript object to string
* @param {object} object - The object to convert to convert
* @param {ClassMetadata} classMetadata - the class metadata
* @return {string} the content of the request
*/
}, {
key: 'deserializeList',
value: function deserializeList(rawListData, classMetadata, response) {
var objectList = this.decodeList(rawListData, classMetadata, response);
return this.denormalizeList(objectList, classMetadata, response);
}
}]);
return Serializer;
}();
}, {
key: 'encodeItem',
value: function encodeItem(object, classMetadata) {
throw new TypeError('`encodeItem` method must be implemented');
}
/* eslint no-unused-vars: 0 */
var JsSerializer = function (_Serializer) {
inherits(JsSerializer, _Serializer);
/**
* convert an entity to string that will be sent as the request content
* @param {any} entity - The entity to convert
* @param {ClassMetadata} classMetadata - the class metadata
* @return {string} the content of the request
*/
function JsSerializer() {
classCallCheck(this, JsSerializer);
return possibleConstructorReturn(this, (JsSerializer.__proto__ || Object.getPrototypeOf(JsSerializer)).apply(this, arguments));
}
}, {
key: 'serializeItem',
value: function serializeItem(object, classMetadata) {
var noralizedData = this.normalizeItem(object, classMetadata);
return this.encodeItem(noralizedData, classMetadata);
}
createClass(JsSerializer, [{
key: 'encodeItem',
value: function encodeItem(object, classMetadata) {
return JSON.stringify(object);
}
}, {
key: 'decodeItem',
value: function decodeItem(rawData, classMetadata, response) {
return JSON.parse(rawData);
}
}, {
key: 'decodeList',
value: function decodeList(rawListData, classMetadata, response) {
return JSON.parse(rawListData);
}
}]);
return JsSerializer;
}(Serializer);
/**
* convert a plain object to an entity
* @param {string} object - The plain javascript object
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {any} an entity
*/
// "fork" of https://github.com/facebook/immutable-js/blob/v4.0.0-rc.9/src/Predicates.js
// because tree-shaking does not seems to work as expected
}, {
key: 'denormalizeItem',
value: function denormalizeItem(object, classMetadata, response) {
return object;
}
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* convert a string containing an object to a plain javascript object
* @param {string} rawData - The string fetched from the response
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {object} the normalized object
*/
function isImmutable(maybeImmutable) {
return isCollection(maybeImmutable) || isRecord(maybeImmutable);
}
}, {
key: 'decodeItem',
value: function decodeItem(rawData, classMetadata, response) {
throw new TypeError('`decodeItem` method must be implemented');
}
function isCollection(maybeCollection) {
return !!(maybeCollection && maybeCollection[IS_ITERABLE_SENTINEL]);
}
/**
* convert a string containing an object to an entity
* @param {string} rawData - The string fetched from the response
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {object} the entity
*/
}, {
key: 'deserializeItem',
value: function deserializeItem(rawData, classMetadata, response) {
var object = this.decodeItem(rawData, classMetadata, response);
return this.denormalizeItem(object, classMetadata, response);
}
/**
* convert a plain object list to an entity list
* @param {array} objectList - The plain javascript object list
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {any} a list of entities
*/
}, {
key: 'denormalizeList',
value: function denormalizeList(objectList, classMetadata, response) {
return objectList;
}
/**
* convert a string containing a list of objects to a list of plain javascript objects
* @param {string} rawListData - The string fetched from the response
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {any} a list of normalized objects
*/
}, {
key: 'decodeList',
value: function decodeList(rawListData, classMetadata, response) {
throw new TypeError('`deserializeList` method must be implemented');
}
/**
* convert a string containing a list of objects to a list of entities
* @param {string} rawListData - The string fetched from the response
* @param {ClassMetadata} classMetadata - the class metadata
* @param {object} response - the HTTP response
* @return {any} a list of entities
*/
}, {
key: 'deserializeList',
value: function deserializeList(rawListData, classMetadata, response) {
var objectList = this.decodeList(rawListData, classMetadata, response);
return this.denormalizeList(objectList, classMetadata, response);
}
}]);
return Serializer;
}();
/* eslint no-unused-vars: 0 */
function isRecord(maybeRecord) {
return !!(maybeRecord && maybeRecord[IS_RECORD_SENTINEL]);
}
var JsSerializer = function (_Serializer) {
inherits(JsSerializer, _Serializer);
function JsSerializer() {
classCallCheck(this, JsSerializer);
return possibleConstructorReturn(this, (JsSerializer.__proto__ || Object.getPrototypeOf(JsSerializer)).apply(this, arguments));
}
createClass(JsSerializer, [{
key: 'encodeItem',
value: function encodeItem(object, classMetadata) {
return JSON.stringify(object);
}
}, {
key: 'decodeItem',
value: function decodeItem(rawData, classMetadata, response) {
return JSON.parse(rawData);
}
}, {
key: 'decodeList',
value: function decodeList(rawListData, classMetadata, response) {
return JSON.parse(rawListData);
}
}]);
return JsSerializer;
}(Serializer);
var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
// "fork" of https://github.com/facebook/immutable-js/blob/v4.0.0-rc.9/src/Predicates.js
// because tree-shaking does not seems to work as expected
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function isImmutable(maybeImmutable) {
return isCollection(maybeImmutable) || isRecord(maybeImmutable);
}
var IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@';
function isCollection(maybeCollection) {
return !!(maybeCollection && maybeCollection[IS_ITERABLE_SENTINEL]);
}
/**
* deep comparaison between objects
*/
function objectDiffers(left, right) {
var result = diff(left, right);
return result && result.length > 0;
}
/**
* get the id of an entity or return itself if string
*/
function getEntityId(stringOrEntity, idSerializedKey) {
if ((typeof stringOrEntity === 'undefined' ? 'undefined' : _typeof(stringOrEntity)) !== 'object') {
return stringOrEntity;
function isRecord(maybeRecord) {
return !!(maybeRecord && maybeRecord[IS_RECORD_SENTINEL]);
}
return stringOrEntity[idSerializedKey];
}
/**
* find old relation value from the new relation id
* if not found, returs the default serilazed model
*/
function findOldRelation(newRelationValue, oldRelationValue, classMetadata) {
var idSerializedKey = classMetadata.getIdentifierAttribute().serializedKey;
var relationValueId = getEntityId(newRelationValue, idSerializedKey);
var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
var IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@';
var foundValue = oldRelationValue && oldRelationValue.find(function (innerOldRelationValue) {
var oldRelationValueId = getEntityId(innerOldRelationValue, idSerializedKey);
/**
* deep comparaison between objects
*/
function objectDiffers(left, right) {
var result = diff(left, right);
return relationValueId === oldRelationValueId;
});
return result && result.length > 0;
}
if (foundValue) {
return foundValue;
/**
* get the id of an entity or return itself if string
*/
function getEntityId(stringOrEntity, idSerializedKey) {
if ((typeof stringOrEntity === 'undefined' ? 'undefined' : _typeof(stringOrEntity)) !== 'object') {
return stringOrEntity;
}
return stringOrEntity[idSerializedKey];
}
return classMetadata.getDefaultSerializedModel();
}
/**
* find old relation value from the new relation id
* if not found, returs the default serilazed model
*/
function findOldRelation(newRelationValue, oldRelationValue, classMetadata) {
var idSerializedKey = classMetadata.getIdentifierAttribute().serializedKey;
var relationValueId = getEntityId(newRelationValue, idSerializedKey);
/**
* add all identifier from one to many relation list
*/
function getIdentifierForList(newValue, idSerializedKey) {
return newValue.map(function (value) {
if (Object.keys(value).includes(idSerializedKey)) {
return defineProperty({}, idSerializedKey, value[idSerializedKey]);
} else if (typeof value === 'string') {
return value;
}
var foundValue = oldRelationValue && oldRelationValue.find(function (innerOldRelationValue) {
var oldRelationValueId = getEntityId(innerOldRelationValue, idSerializedKey);
throw new TypeError('new value should include a list of string or objects containing the serialized key');
});
}
return relationValueId === oldRelationValueId;
});
var UnitOfWork = function () {
function UnitOfWork(mapping) {
classCallCheck(this, UnitOfWork);
if (foundValue) {
return foundValue;
}
this.mapping = mapping;
this._storage = {};
return classMetadata.getDefaultSerializedModel();
}
createClass(UnitOfWork, [{
key: 'registerClean',
value: function registerClean(id, entity) {
if (isImmutable(entity)) {
this._storage[id] = entity;
} else {
this._storage[id] = Object.assign({}, entity);
/**
* add all identifier from one to many relation list
*/
function getIdentifierForList(newValue, idSerializedKey) {
return newValue.map(function (value) {
if (Object.keys(value).includes(idSerializedKey)) {
return defineProperty({}, idSerializedKey, value[idSerializedKey]);
} else if (typeof value === 'string') {
return value;
}
}
}, {
key: 'getDirtyEntity',
value: function getDirtyEntity(id) {
return this._storage[id];
}
}, {
key: 'clear',
value: function clear(id) {
delete this._storage[id];
}
}, {
key: 'getDirtyData',
value: function getDirtyData(newSerializedModel, oldSerializedModel, classMetadata) {
return this._getDirtyFields(newSerializedModel, oldSerializedModel, classMetadata);
}
}, {
key: '_getDirtyFieldsForAttribute',
value: function _getDirtyFieldsForAttribute(dirtyFieldsParam, key, attribute, oldValue, newValue) {
var dirtyFields = dirtyFieldsParam;
if (attribute.type === 'object') {
if (oldValue === undefined || objectDiffers(oldValue, newValue)) {
dirtyFields[key] = newValue;
}
} else if (oldValue !== newValue) {
dirtyFields[key] = newValue;
}
throw new TypeError('new value should include a list of string or objects containing the serialized key');
});
}
return dirtyFields;
var UnitOfWork = function () {
function UnitOfWork(mapping) {
classCallCheck(this, UnitOfWork);
this.mapping = mapping;
this._storage = {};
}
}, {
key: '_getDirtyFieldsForManyToOne',
value: function _getDirtyFieldsForManyToOne(dirtyFieldsParam, key, oldValue, newValue, relationMetadata, idSerializedKey) {
var dirtyFields = dirtyFieldsParam;
if (oldValue !== newValue) {
if (newValue === null) {
dirtyFields[key] = null;
return dirtyFields;
createClass(UnitOfWork, [{
key: 'registerClean',
value: function registerClean(id, entity) {
if (isImmutable(entity)) {
this._storage[id] = entity;
} else {
this._storage[id] = Object.assign({}, entity);
}
}
}, {
key: 'getDirtyEntity',
value: function getDirtyEntity(id) {
return this._storage[id];
}
}, {
key: 'clear',
value: function clear(id) {
delete this._storage[id];
}
}, {
key: 'getDirtyData',
value: function getDirtyData(newSerializedModel, oldSerializedModel, classMetadata) {
return this._getDirtyFields(newSerializedModel, oldSerializedModel, classMetadata);
}
}, {
key: '_getDirtyFieldsForAttribute',
value: function _getDirtyFieldsForAttribute(dirtyFieldsParam, key, attribute, oldValue, newValue) {
var dirtyFields = dirtyFieldsParam;
if (typeof oldValue === 'string' || typeof newValue === 'string') {
if (attribute.type === 'object') {
if (oldValue === undefined || objectDiffers(oldValue, newValue)) {
dirtyFields[key] = newValue;
}
} else if (oldValue !== newValue) {
dirtyFields[key] = newValue;
}
var recursiveDiff = this._getDirtyFields(newValue, oldValue, relationMetadata);
if (Object.keys(recursiveDiff).length > 0) {
recursiveDiff[idSerializedKey] = getEntityId(newValue, idSerializedKey);
dirtyFields[key] = recursiveDiff;
}
return dirtyFields;
}
}, {
key: '_getDirtyFieldsForManyToOne',
value: function _getDirtyFieldsForManyToOne(dirtyFieldsParam, key, oldValue, newValue, relationMetadata, idSerializedKey) {
var dirtyFields = dirtyFieldsParam;
if (oldValue !== newValue) {
if (newValue === null) {
dirtyFields[key] = null;
return dirtyFields;
}
}, {
key: '_getDirtyFieldsForOneToMany',
value: function _getDirtyFieldsForOneToMany(dirtyFieldsParam, key, idSerializedKey, relationMetadata, oldValue, newValue) {
var _this = this;
return dirtyFields;
}
var dirtyFields = dirtyFieldsParam;
var newValueLength = newValue ? newValue.length : 0;
var oldValueLength = oldValue ? oldValue.length : 0;
if (typeof oldValue === 'string' || typeof newValue === 'string') {
dirtyFields[key] = newValue;
}
// number of items changed
if (newValueLength !== oldValueLength) {
dirtyFields[key] = getIdentifierForList(newValue, idSerializedKey);
}
var recursiveDiff = this._getDirtyFields(newValue, oldValue, relationMetadata);
if (newValue && newValue.length > 0) {
if (dirtyFields[key] === undefined) {
dirtyFields[key] = [];
if (Object.keys(recursiveDiff).length > 0) {
recursiveDiff[idSerializedKey] = getEntityId(newValue, idSerializedKey);
dirtyFields[key] = recursiveDiff;
}
}
var relationList = newValue;
return dirtyFields;
}
}, {
key: '_getDirtyFieldsForOneToMany',
value: function _getDirtyFieldsForOneToMany(dirtyFieldsParam, key, idSerializedKey, relationMetadata, oldValue, newValue) {
var _this = this;
relationList.forEach(function (newRelationValue, relationAttributeName) {
var oldRelationValue = findOldRelation(newRelationValue, oldValue, relationMetadata);
var dirtyFields = dirtyFieldsParam;
var newValueLength = newValue ? newValue.length : 0;
var oldValueLength = oldValue ? oldValue.length : 0;
if (newRelationValue !== oldRelationValue) {
if (typeof newRelationValue === 'string' || typeof oldRelationValue === 'string') {
dirtyFields[key][relationAttributeName] = newRelationValue;
// number of items changed
if (newValueLength !== oldValueLength) {
dirtyFields[key] = getIdentifierForList(newValue, idSerializedKey);
}
return;
}
if (newValue && newValue.length > 0) {
if (dirtyFields[key] === undefined) {
dirtyFields[key] = [];
}
var recursiveDiff = _this._getDirtyFields(newRelationValue, oldRelationValue, relationMetadata);
var relationList = newValue;
if (Object.keys(recursiveDiff).length > 0) {
var entityId = getEntityId(newRelationValue, idSerializedKey);
relationList.forEach(function (newRelationValue, relationAttributeName) {
var oldRelationValue = findOldRelation(newRelationValue, oldValue, relationMetadata);
if (entityId !== null) {
recursiveDiff[idSerializedKey] = entityId;
if (newRelationValue !== oldRelationValue) {
if (typeof newRelationValue === 'string' || typeof oldRelationValue === 'string') {
dirtyFields[key][relationAttributeName] = newRelationValue;
return;
}
if (dirtyFields[key][relationAttributeName]) {
Object.assign(dirtyFields[key][relationAttributeName], recursiveDiff);
} else {
dirtyFields[key][relationAttributeName] = recursiveDiff;
var recursiveDiff = _this._getDirtyFields(newRelationValue, oldRelationValue, relationMetadata);
if (Object.keys(recursiveDiff).length > 0) {
var entityId = getEntityId(newRelationValue, idSerializedKey);
if (entityId !== null) {
recursiveDiff[idSerializedKey] = entityId;
}
if (dirtyFields[key][relationAttributeName]) {
Object.assign(dirtyFields[key][relationAttributeName], recursiveDiff);
} else {
dirtyFields[key][relationAttributeName] = recursiveDiff;
}
}
}
});
if (dirtyFields[key].length > 0) {
// add identifier because one or more object linked has been updated
// see test: 'get dirty data many to one update item'
dirtyFields[key] = Object.assign(getIdentifierForList(newValue, idSerializedKey), dirtyFields[key]);
} else {
// no changes, no need to send the key with an empty array as value
delete dirtyFields[key];
}
});
}
if (dirtyFields[key].length > 0) {
// add identifier because one or more object linked has been updated
// see test: 'get dirty data many to one update item'
dirtyFields[key] = Object.assign(getIdentifierForList(newValue, idSerializedKey), dirtyFields[key]);
} else {
// no changes, no need to send the key with an empty array as value
delete dirtyFields[key];
}
return dirtyFields;
}
}, {
key: '_getDirtyFields',
value: function _getDirtyFields(newSerializedModel, oldSerializedModel, classMetadata) {
var _this2 = this;
return dirtyFields;
}
}, {
key: '_getDirtyFields',
value: function _getDirtyFields(newSerializedModel, oldSerializedModel, classMetadata) {
var _this2 = this;
var dirtyFields = {};
var dirtyFields = {};
Object.values(classMetadata.getAttributeList()).forEach(function (attribute) {
var key = attribute.attributeName;
var newValue = newSerializedModel[key];
var oldValue = oldSerializedModel ? oldSerializedModel[key] : null;
Object.values(classMetadata.getAttributeList()).forEach(function (attribute) {
var key = attribute.attributeName;
var newValue = newSerializedModel[key];
var oldValue = oldSerializedModel ? oldSerializedModel[key] : null;
var currentRelation = classMetadata.getRelation(attribute.serializedKey);
var currentRelation = classMetadata.getRelation(attribute.serializedKey);
if (newValue === undefined) {
return;
}
if (newValue === undefined) {
return;
}
// not a relation
if (!currentRelation) {
dirtyFields = _this2._getDirtyFieldsForAttribute(dirtyFields, key, attribute, oldValue, newValue);
// not a relation
if (!currentRelation) {
dirtyFields = _this2._getDirtyFieldsForAttribute(dirtyFields, key, attribute, oldValue, newValue);
return;
}
return;
}
var relationMetadata = _this2.mapping.getClassMetadataByKey(currentRelation.targetMetadataKey);
var relationMetadata = _this2.mapping.getClassMetadataByKey(currentRelation.targetMetadataKey);
if (!relationMetadata) {
throw new TypeError('relation metadata is not set for relation ' + classMetadata.key + '.' + currentRelation.targetMetadataKey);
}
if (!relationMetadata) {
throw new TypeError('relation metadata is not set for relation ' + classMetadata.key + '.' + currentRelation.targetMetadataKey);
}
var idSerializedKey = relationMetadata ? relationMetadata.getIdentifierAttribute().serializedKey : null;
var idSerializedKey = relationMetadata ? relationMetadata.getIdentifierAttribute().serializedKey : null;
// MANY_TO_ONE relation
if (currentRelation.isManyToOne()) {
dirtyFields = _this2._getDirtyFieldsForManyToOne(dirtyFields, key, oldValue, newValue, relationMetadata, idSerializedKey);
// MANY_TO_ONE relation
if (currentRelation.isManyToOne()) {
dirtyFields = _this2._getDirtyFieldsForManyToOne(dirtyFields, key, oldValue, newValue, relationMetadata, idSerializedKey);
return;
}
return;
}
// ONE_TO_MANY relation
dirtyFields = _this2._getDirtyFieldsForOneToMany(dirtyFields, key, idSerializedKey, relationMetadata, oldValue, newValue);
});
// ONE_TO_MANY relation
dirtyFields = _this2._getDirtyFieldsForOneToMany(dirtyFields, key, idSerializedKey, relationMetadata, oldValue, newValue);
});
return dirtyFields;
}
}]);
return UnitOfWork;
}();
return dirtyFields;
}
}]);
return UnitOfWork;
}();
var DEFAULT_CONFIG = {
collectionKey: 'hydra:member'
};
var DEFAULT_CONFIG = {
collectionKey: 'hydra:member'
};
var Mapping = function () {
function Mapping() {
var idPrefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, Mapping);
var Mapping = function () {
function Mapping() {
var idPrefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, Mapping);
this.idPrefix = idPrefix;
this.idPrefix = idPrefix;
this._idPrefixLength = idPrefix.length;
this._classMetadataList = [];
this._idPrefixLength = idPrefix.length;
this._classMetadataList = [];
this.setConfig(config);
}
this.setConfig(config);
}
createClass(Mapping, [{
key: 'getConfig',
value: function getConfig() {
return this._config;
}
}, {
key: 'setConfig',
value: function setConfig(config) {
this._config = Object.assign({}, DEFAULT_CONFIG, config);
}
}, {
key: 'setMapping',
value: function setMapping() {
var classMetadataList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
createClass(Mapping, [{
key: 'getConfig',
value: function getConfig() {
return this._config;
}
}, {
key: 'setConfig',
value: function setConfig(config) {
this._config = Object.assign({}, DEFAULT_CONFIG, config);
}
}, {
key: 'setMapping',
value: function setMapping() {
var classMetadataList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
this._classMetadataList = classMetadataList;
}
}, {
key: 'getMappingKeys',
value: function getMappingKeys() {
return this._classMetadataList.map(function (classMetadata) {
return classMetadata.key;
});
}
}, {
key: 'getClassMetadataByKey',
value: function getClassMetadataByKey(key) {
var filterList = this._classMetadataList.filter(function (classMetadata) {
return classMetadata.key === key;
});
this._classMetadataList = classMetadataList;
}
}, {
key: 'getMappingKeys',
value: function getMappingKeys() {
return this._classMetadataList.map(function (classMetadata) {
return classMetadata.key;
});
}
}, {
key: 'getClassMetadataByKey',
value: function getClassMetadataByKey(key) {
var filterList = this._classMetadataList.filter(function (classMetadata) {
return classMetadata.key === key;
});
return filterList.length > 0 ? filterList[0] : null;
}
}, {
key: 'isMappingValid',
value: function isMappingValid() {
var _this = this;
return filterList.length > 0 ? filterList[0] : null;
}
}, {
key: 'isMappingValid',
value: function isMappingValid() {
var _this = this;
return !this._classMetadataList.some(function (classMetadata) {
// check that the relations exists
var errorList = Object.values(classMetadata.getAttributeList()).map(function (attribute) {
var relation = classMetadata.getRelation(attribute.serializedKey);
return !this._classMetadataList.some(function (classMetadata) {
// check that the relations exists
var errorList = Object.values(classMetadata.getAttributeList()).map(function (attribute) {
var relation = classMetadata.getRelation(attribute.serializedKey);
if (!relation) {
// attribute can not be "invalid" (for now ?)
return false;
}
if (!relation) {
// attribute can not be "invalid" (for now ?)
return false;
}
var relationMetadata = _this.getClassMetadataByKey(relation.targetMetadataKey);
var relationMetadata = _this.getClassMetadataByKey(relation.targetMetadataKey);
// relation name seems weird
if (relation.isManyToOne() && attribute.attributeName.endsWith('List')) {
return '"' + classMetadata.key + '.' + attribute.serializedKey + ' is defined as a MANY_TO_ONE relation, but the attribute name ends with "List".';
}
// relation name seems weird
if (relation.isManyToOne() && attribute.attributeName.endsWith('List')) {
return '"' + classMetadata.key + '.' + attribute.serializedKey + ' is defined as a MANY_TO_ONE relation, but the attribute name ends with "List".';
}
if (relation.isOneToMany()) {
var message = '"' + classMetadata.key + '.' + attribute.serializedKey + ' is defined as a ONE_TO_MANY relation, but the attribute name is nor plural not ends with "List".';
if (relation.isOneToMany()) {
var message = '"' + classMetadata.key + '.' + attribute.serializedKey + ' is defined as a ONE_TO_MANY relation, but the attribute name is nor plural not ends with "List".';
var endsWithList = attribute.attributeName.endsWith('List');
var endsWithList = attribute.attributeName.endsWith('List');
try {
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
var pluralize = require('pluralize');
if (!endsWithList && !pluralize.isPlural(attribute.attributeName)) {
return message;
try {
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
var pluralize = require('pluralize');
if (!endsWithList && !pluralize.isPlural(attribute.attributeName)) {
return message;
}
} catch (e) {
if (!endsWithList) {
return message;
}
}
} catch (e) {
if (!endsWithList) {
return message;
}
}
}
// no error if there is metadata linked
if (!relationMetadata) {
return '"' + classMetadata.key + '.' + attribute.serializedKey + '" defined a relation to the metadata named "' + relation.targetMetadataKey + '" but this metadata is not knowned by the mapping';
// no error if there is metadata linked
if (!relationMetadata) {
return '"' + classMetadata.key + '.' + attribute.serializedKey + '" defined a relation to the metadata named "' + relation.targetMetadataKey + '" but this metadata is not knowned by the mapping';
}
return false;
});
if (!classMetadata.getIdentifierAttribute()) {
errorList.push('"' + classMetadata.key + '" has no identifier attribute set');
}
return false;
});
var nbError = errorList.filter(function (error) {
if (error) {
// eslint-disable-next-line no-console
console.warn(error);
}
if (!classMetadata.getIdentifierAttribute()) {
errorList.push('"' + classMetadata.key + '" has no identifier attribute set');
}
return error;
});
var nbError = errorList.filter(function (error) {
if (error) {
// eslint-disable-next-line no-console
console.warn(error);
}
return error;
return nbError.length > 0;
});
}
}]);
return Mapping;
}();
return nbError.length > 0;
});
}
}]);
return Mapping;
}();
var RestClientSdk = function () {
function RestClientSdk(tokenStorage, config, mapping) {
var serializer = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new JsSerializer();
classCallCheck(this, RestClientSdk);
var RestClientSdk = function () {
function RestClientSdk(tokenStorage, config, mapping) {
var serializer = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new JsSerializer();
classCallCheck(this, RestClientSdk);
this._checkConfigValidity(config);
this._checkConfigValidity(config);
if (!(mapping instanceof Mapping)) {
throw new TypeError('mapping should be an instance of `Mapping`');
}
if (!(mapping instanceof Mapping)) {
throw new TypeError('mapping should be an instance of `Mapping`');
}
this.config = this._mergeWithBaseConfig(config);
this.tokenStorage = tokenStorage;
this.serializer = serializer;
this.mapping = mapping;
this.config = this._mergeWithBaseConfig(config);
this.tokenStorage = tokenStorage;
this.serializer = serializer;
this.mapping = mapping;
this.unitOfWork = new UnitOfWork(this.mapping);
this.unitOfWork = new UnitOfWork(this.mapping);
this._repositoryList = {};
}
this._repositoryList = {};
}
createClass(RestClientSdk, [{
key: 'getRepository',
value: function getRepository(key) {
if (!this._repositoryList[key]) {
var metadata = this.mapping.getClassMetadataByKey(key);
// eslint-disable-next-line new-cap
this._repositoryList[key] = new metadata.repositoryClass(this, metadata);
}
createClass(RestClientSdk, [{
key: 'getRepository',
value: function getRepository(key) {
if (!this._repositoryList[key]) {
var metadata = this.mapping.getClassMetadataByKey(key);
// eslint-disable-next-line new-cap
this._repositoryList[key] = new metadata.repositoryClass(this, metadata);
return this._repositoryList[key];
}
}, {
key: '_mergeWithBaseConfig',
value: function _mergeWithBaseConfig(config) {
var newConfig = config;
newConfig.useDefaultParameters = config.useDefaultParameters === undefined ? true : config.useDefaultParameters;
return this._repositoryList[key];
}
}, {
key: '_mergeWithBaseConfig',
value: function _mergeWithBaseConfig(config) {
var newConfig = config;
newConfig.useDefaultParameters = config.useDefaultParameters === undefined ? true : config.useDefaultParameters;
newConfig.authorizationType = config.authorizationType || 'Bearer';
newConfig.authorizationType = config.authorizationType || 'Bearer';
return newConfig;
}
}, {
key: '_checkConfigValidity',
value: function _checkConfigValidity(config) {
if (!(config && config.path && config.scheme)) {
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');
return newConfig;
}
}
}]);
return RestClientSdk;
}();
}, {
key: '_checkConfigValidity',
value: function _checkConfigValidity(config) {
if (!(config && config.path && config.scheme)) {
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');
}
}
}]);
return RestClientSdk;
}();
/**
* It's a bit tricky to extends native errors
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
*/
/**
* It's a bit tricky to extends native errors
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
*/
function HttpError(message, baseResponse) {
this.name = 'BadRequestError';
this.message = message || 'Bad request';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
HttpError.prototype = Object.create(Error.prototype);
HttpError.prototype.constructor = HttpError;
function HttpError(message, baseResponse) {
this.name = 'BadRequestError';
this.message = message || 'Bad request';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
HttpError.prototype = Object.create(Error.prototype);
HttpError.prototype.constructor = HttpError;
// 400
function BadRequestError(message, baseResponse) {
this.name = 'BadRequestError';
this.message = message || 'Bad request';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
BadRequestError.prototype = Object.create(HttpError.prototype);
BadRequestError.prototype.constructor = BadRequestError;
// 400
function BadRequestError(message, baseResponse) {
this.name = 'BadRequestError';
this.message = message || 'Bad request';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
BadRequestError.prototype = Object.create(HttpError.prototype);
BadRequestError.prototype.constructor = BadRequestError;
// 401
function AccessDeniedError(message, baseResponse) {
this.name = 'AccessDeniedError';
this.message = message || 'Access denied';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
AccessDeniedError.prototype = Object.create(BadRequestError.prototype);
AccessDeniedError.prototype.constructor = AccessDeniedError;
// 401
function AccessDeniedError(message, baseResponse) {
this.name = 'AccessDeniedError';
this.message = message || 'Access denied';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
AccessDeniedError.prototype = Object.create(BadRequestError.prototype);
AccessDeniedError.prototype.constructor = AccessDeniedError;
// 403
function ForbiddenError(message, baseResponse) {
this.name = 'ForbiddenError';
this.message = message || 'Forbidden';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
ForbiddenError.prototype = Object.create(BadRequestError.prototype);
ForbiddenError.prototype.constructor = ForbiddenError;
// 403
function ForbiddenError(message, baseResponse) {
this.name = 'ForbiddenError';
this.message = message || 'Forbidden';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
ForbiddenError.prototype = Object.create(BadRequestError.prototype);
ForbiddenError.prototype.constructor = ForbiddenError;
// 404
function ResourceNotFoundError(message, baseResponse) {
this.name = 'ResourceNotFoundError';
this.message = message || 'Resource is not found';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
ResourceNotFoundError.prototype = Object.create(BadRequestError.prototype);
ResourceNotFoundError.prototype.constructor = ResourceNotFoundError;
// 404
function ResourceNotFoundError(message, baseResponse) {
this.name = 'ResourceNotFoundError';
this.message = message || 'Resource is not found';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
ResourceNotFoundError.prototype = Object.create(BadRequestError.prototype);
ResourceNotFoundError.prototype.constructor = ResourceNotFoundError;
// 500
function InternalServerError(message, baseResponse) {
this.name = 'InternalServerError';
this.message = message || 'Internal server error';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
InternalServerError.prototype = Object.create(HttpError.prototype);
InternalServerError.prototype.constructor = InternalServerError;
// 500
function InternalServerError(message, baseResponse) {
this.name = 'InternalServerError';
this.message = message || 'Internal server error';
this.baseResponse = baseResponse;
this.stack = new Error().stack;
}
InternalServerError.prototype = Object.create(HttpError.prototype);
InternalServerError.prototype.constructor = InternalServerError;
function handleBadResponse(response) {
switch (true) {
case response.status === 403:
throw new ForbiddenError(null, response);
function handleBadResponse(response) {
switch (true) {
case response.status === 403:
throw new ForbiddenError(null, response);
case response.status === 404:
throw new ResourceNotFoundError(null, response);
case response.status === 404:
throw new ResourceNotFoundError(null, response);
case response.status >= 400 && response.status < 500:
throw new BadRequestError(null, response);
case response.status >= 400 && response.status < 500:
throw new BadRequestError(null, response);
case response.status >= 500 && response.status < 600:
throw new InternalServerError(null, response);
case response.status >= 500 && response.status < 600:
throw new InternalServerError(null, response);
default:
return new Error('Unexpected error, status code is ' + response.status);
default:
return new Error('Unexpected error, status code is ' + response.status);
}
}
}
var AbstractClient = function () {
function AbstractClient(sdk, metadata) {
classCallCheck(this, AbstractClient);
var AbstractClient = function () {
function AbstractClient(sdk, metadata) {
classCallCheck(this, AbstractClient);
this.sdk = sdk;
this._tokenStorage = sdk.tokenStorage;
this.serializer = sdk.serializer;
this.metadata = metadata;
}
createClass(AbstractClient, [{
key: 'getDefaultParameters',
value: function getDefaultParameters() {
return [];
this.sdk = sdk;
this._tokenStorage = sdk.tokenStorage;
this.serializer = sdk.serializer;
this.metadata = metadata;
}
// eslint-disable-next-line no-unused-vars
createClass(AbstractClient, [{
key: 'getDefaultParameters',
value: function getDefaultParameters() {
return [];
}
}, {
key: 'getPathBase',
value: function getPathBase(pathParameters) {
return '/' + this.metadata.pathRoot;
}
}, {
key: 'getEntityURI',
value: function getEntityURI(entity) {
var idValue = this._getEntityIdentifier(entity);
// eslint-disable-next-line no-unused-vars
if (Number.isFinite(idValue)) {
idValue = idValue.toString();
}, {
key: 'getPathBase',
value: function getPathBase(pathParameters) {
return '/' + this.metadata.pathRoot;
}
}, {
key: 'getEntityURI',
value: function getEntityURI(entity) {
var idValue = this._getEntityIdentifier(entity);
var pathBase = this.getPathBase({});
if (idValue.indexOf(pathBase) > -1) {
return idValue;
if (Number.isFinite(idValue)) {
idValue = idValue.toString();
}
var pathBase = this.getPathBase({});
if (idValue.indexOf(pathBase) > -1) {
return idValue;
}
return pathBase + '/' + idValue;
}
return pathBase + '/' + idValue;
}
}, {
key: 'find',
value: function find(id) {
var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var pathParameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
}, {
key: 'find',
value: function find(id) {
var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var pathParameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var url = this._generateUrlFromParams(queryParam, pathParameters, id);
var url = this._generateUrlFromParams(queryParam, pathParameters, id);
return this.deserializeResponse(this.authorizedFetch(url), 'item');
}
}, {
key: 'findBy',
value: function findBy(queryParam) {
var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.deserializeResponse(this.authorizedFetch(url), 'item');
}
}, {
key: 'findBy',
value: function findBy(queryParam) {
var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var url = this._generateUrlFromParams(queryParam, pathParameters);
var url = this._generateUrlFromParams(queryParam, pathParameters);
return this.deserializeResponse(this.authorizedFetch(url), 'list');
}
}, {
key: 'findAll',
value: function findAll() {
var queryParam = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.deserializeResponse(this.authorizedFetch(url), 'list');
}
}, {
key: 'findAll',
value: function findAll() {
var queryParam = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.findBy(queryParam, pathParameters);
}
}, {
key: 'create',
value: function create(entity) {
var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var pathParameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
return this.findBy(queryParam, pathParameters);
}
}, {
key: 'create',
value: function create(entity) {
var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var pathParameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var url = new URI(this.getPathBase(pathParameters));
url.addSearch(queryParam);
var url = new URI(this.getPathBase(pathParameters));
url.addSearch(queryParam);
var oldSerializedModel = this.metadata.getDefaultSerializedModel();
var newSerializedModel = this.serializer.normalizeItem(entity, this.metadata);
var oldSerializedModel = this.metadata.getDefaultSerializedModel();
var newSerializedModel = this.serializer.normalizeItem(entity, this.metadata);
var diff$$1 = this.sdk.unitOfWork.getDirtyData(newSerializedModel, oldSerializedModel, this.metadata);
var diff$$1 = this.sdk.unitOfWork.getDirtyData(newSerializedModel, oldSerializedModel, this.metadata);
return this.deserializeResponse(this.authorizedFetch(url, {
method: 'POST',
body: this.serializer.encodeItem(diff$$1, this.metadata)
}), 'item');
}
}, {
key: 'update',
value: function update(entity) {
var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.deserializeResponse(this.authorizedFetch(url, {
method: 'POST',
body: this.serializer.encodeItem(diff$$1, this.metadata)
}), 'item');
}
}, {
key: 'update',
value: function update(entity) {
var queryParam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var url = new URI(this.getEntityURI(entity));
url.addSearch(queryParam);
var url = new URI(this.getEntityURI(entity));
url.addSearch(queryParam);
var newSerializedModel = this.serializer.normalizeItem(entity, this.metadata);
var newSerializedModel = this.serializer.normalizeItem(entity, this.metadata);
var identifier = this._getEntityIdentifier(newSerializedModel);
var oldModel = this.sdk.unitOfWork.getDirtyEntity(identifier);
var identifier = this._getEntityIdentifier(newSerializedModel);
var oldModel = this.sdk.unitOfWork.getDirtyEntity(identifier);
if (oldModel) {
newSerializedModel = this.sdk.unitOfWork.getDirtyData(newSerializedModel, oldModel, this.metadata);
if (oldModel) {
newSerializedModel = this.sdk.unitOfWork.getDirtyData(newSerializedModel, oldModel, this.metadata);
}
return this.deserializeResponse(this.authorizedFetch(url, {
method: 'PUT',
body: this.serializer.encodeItem(newSerializedModel, this.metadata)
}), 'item');
}
}, {
key: 'delete',
value: function _delete(entity) {
var _this = this;
return this.deserializeResponse(this.authorizedFetch(url, {
method: 'PUT',
body: this.serializer.encodeItem(newSerializedModel, this.metadata)
}), 'item');
}
}, {
key: 'delete',
value: function _delete(entity) {
var _this = this;
var url = this.getEntityURI(entity);
var identifier = this._getEntityIdentifier(entity);
var url = this.getEntityURI(entity);
var identifier = this._getEntityIdentifier(entity);
return this.authorizedFetch(url, {
method: 'DELETE'
}).then(function (response) {
_this.sdk.unitOfWork.clear(identifier);
return this.authorizedFetch(url, {
method: 'DELETE'
}).then(function (response) {
_this.sdk.unitOfWork.clear(identifier);
return response;
});
}
}, {
key: 'deserializeResponse',
value: function deserializeResponse(requestPromise, listOrItem) {
var _this2 = this;
return response;
});
}
}, {
key: 'deserializeResponse',
value: function deserializeResponse(requestPromise, listOrItem) {
var _this2 = this;
return requestPromise.then(function (response) {
return response.text().then(function (text) {
return [response, text];
});
}).then(function (_ref) {
var _ref2 = slicedToArray(_ref, 2),
response = _ref2[0],
text = _ref2[1];
return requestPromise.then(function (response) {
return response.text().then(function (text) {
return [response, text];
});
}).then(function (_ref) {
var _ref2 = slicedToArray(_ref, 2),
response = _ref2[0],
text = _ref2[1];
if (listOrItem === 'list') {
// for list, we need to deserialize the result to get an object
var itemList = _this2.serializer.deserializeList(text, _this2.metadata, response);
if (listOrItem === 'list') {
// for list, we need to deserialize the result to get an object
var itemList = _this2.serializer.deserializeList(text, _this2.metadata, response);
// eslint-disable-next-line no-restricted-syntax
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
// eslint-disable-next-line no-restricted-syntax
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = itemList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _decodedItem = _step.value;
try {
for (var _iterator = itemList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _decodedItem = _step.value;
var _identifier = _this2._getEntityIdentifier(_decodedItem);
var normalizedItem = _this2.serializer.normalizeItem(_decodedItem);
var _identifier = _this2._getEntityIdentifier(_decodedItem);
var normalizedItem = _this2.serializer.normalizeItem(_decodedItem);
// then we register the re-normalized item
_this2.sdk.unitOfWork.registerClean(_identifier, normalizedItem);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
// then we register the re-normalized item
_this2.sdk.unitOfWork.registerClean(_identifier, normalizedItem);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
if (_didIteratorError) {
throw _iteratorError;
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return itemList;
}
return itemList;
}
// for items, we can just decode the item (ie. transform it to JS object)
var decodedItem = _this2.serializer.decodeItem(text, _this2.metadata, response);
// for items, we can just decode the item (ie. transform it to JS object)
var decodedItem = _this2.serializer.decodeItem(text, _this2.metadata, response);
// and register it directy without deserializing + renormalizing
var identifier = _this2._getEntityIdentifier(decodedItem);
// and register it directy without deserializing + renormalizing
var identifier = _this2._getEntityIdentifier(decodedItem);
// and finally return the denormalized item
var item = _this2.serializer.denormalizeItem(decodedItem, _this2.metadata, response);
// and finally return the denormalized item
var item = _this2.serializer.denormalizeItem(decodedItem, _this2.metadata, response);
_this2.sdk.unitOfWork.registerClean(identifier, _this2.serializer.normalizeItem(item));
_this2.sdk.unitOfWork.registerClean(identifier, _this2.serializer.normalizeItem(item));
return item;
});
}
}, {
key: 'makeUri',
value: function makeUri(input) {
var url = input instanceof URI ? input : new URI(input);
url.host(this.sdk.config.path).scheme(this.sdk.config.scheme);
if (this.sdk.config.port) {
url.port(this.sdk.config.port);
return item;
});
}
}, {
key: 'makeUri',
value: function makeUri(input) {
var url = input instanceof URI ? input : new URI(input);
url.host(this.sdk.config.path).scheme(this.sdk.config.scheme);
if (this.sdk.mapping.idPrefix) {
var segments = url.segment();
if ('/' + segments[0] !== this.sdk.mapping.idPrefix) {
segments.unshift(this.sdk.mapping.idPrefix);
url.segment(segments);
if (this.sdk.config.port) {
url.port(this.sdk.config.port);
}
}
return url;
}
}, {
key: 'authorizedFetch',
value: function authorizedFetch(input, init) {
var url = this.makeUri(input);
if (this.sdk.mapping.idPrefix) {
var segments = url.segment();
if ('/' + segments[0] !== this.sdk.mapping.idPrefix) {
segments.unshift(this.sdk.mapping.idPrefix);
url.segment(segments);
}
}
return this._doFetch(url.toString(), init);
}
}, {
key: '_generateUrlFromParams',
value: function _generateUrlFromParams(queryParam) {
var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
return url;
}
}, {
key: 'authorizedFetch',
value: function authorizedFetch(input, init) {
var url = this.makeUri(input);
var params = queryParam;
if (this.sdk.config.useDefaultParameters) {
Object.assign(params, this.getDefaultParameters());
return this._doFetch(url.toString(), init);
}
}, {
key: '_generateUrlFromParams',
value: function _generateUrlFromParams(queryParam) {
var pathParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var pathBase = this.getPathBase(pathParameters);
var params = queryParam;
if (this.sdk.config.useDefaultParameters) {
Object.assign(params, this.getDefaultParameters());
}
var url = null;
if (id) {
var testPathBase = this.sdk.mapping.idPrefix ? '' + this.sdk.mapping.idPrefix + pathBase : pathBase;
var pathBase = this.getPathBase(pathParameters);
if (typeof id === 'string' && id.startsWith(testPathBase)) {
url = new URI(id);
var url = null;
if (id) {
var testPathBase = this.sdk.mapping.idPrefix ? '' + this.sdk.mapping.idPrefix + pathBase : pathBase;
if (typeof id === 'string' && id.startsWith(testPathBase)) {
url = new URI(id);
} else {
url = new URI(pathBase + '/' + id);
}
} else {
url = new URI(pathBase + '/' + id);
url = new URI(pathBase);
}
} else {
url = new URI(pathBase);
}
if (params) {
url.addSearch(params);
if (params) {
url.addSearch(params);
}
return url;
}
}, {
key: '_doFetch',
value: function _doFetch(input, init) {
var _this3 = this;
return url;
}
}, {
key: '_doFetch',
value: function _doFetch(input, init) {
var _this3 = this;
if (!input) {
throw new Error('input is empty');
}
if (!input) {
throw new Error('input is empty');
return this._tokenStorage.getAccessToken().then(function (token) {
return _this3._fetchWithToken(token, input, init);
});
}
}, {
key: '_manageAccessDenied',
value: function _manageAccessDenied(response, input, init) {
var _this4 = this;
return this._tokenStorage.getAccessToken().then(function (token) {
return _this3._fetchWithToken(token, input, init);
});
}
}, {
key: '_manageAccessDenied',
value: function _manageAccessDenied(response, input, init) {
var _this4 = this;
return response.json().then(function (body) {
if (body.error === 'invalid_grant') {
switch (body.error_description) {
case 'The access token provided has expired.':
if (_this4._tokenStorage) {
return _this4._tokenStorage.refreshToken().then(function () {
var params = Object.assign({}, init, {
headers: Object.assign({}, init.headers)
});
delete params.headers.Authorization;
return response.json().then(function (body) {
if (body.error === 'invalid_grant') {
switch (body.error_description) {
case 'The access token provided has expired.':
if (_this4._tokenStorage) {
return _this4._tokenStorage.refreshToken().then(function () {
var params = Object.assign({}, init, {
headers: Object.assign({}, init.headers)
return _this4._doFetch(input, params);
}).catch(function () {
throw new AccessDeniedError('Unable to renew access_token', response);
});
delete params.headers.Authorization;
}
return _this4._doFetch(input, params);
}).catch(function () {
throw new AccessDeniedError('Unable to renew access_token', response);
});
}
break;
break;
default:
throw new AccessDeniedError(body.error_description, response);
default:
throw new AccessDeniedError(body.error_description, response);
}
}
}
throw new AccessDeniedError('Unable to access ressource: 401 found !', response);
}).catch(function () {
throw new AccessDeniedError('Unable to access ressource: 401 found !', response);
});
}
}, {
key: '_fetchWithToken',
value: function _fetchWithToken(accessToken, input, init) {
var _this5 = this;
throw new AccessDeniedError('Unable to access ressource: 401 found !', response);
}).catch(function () {
throw new AccessDeniedError('Unable to access ressource: 401 found !', response);
});
}
}, {
key: '_fetchWithToken',
value: function _fetchWithToken(accessToken, input, init) {
var _this5 = this;
var params = init;
var params = init;
var baseHeaders = {
Authorization: this.sdk.config.authorizationType + ' ' + accessToken,
'Content-Type': 'application/json'
};
var baseHeaders = {
Authorization: this.sdk.config.authorizationType + ' ' + accessToken,
'Content-Type': 'application/json'
};
var currentUri = (typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.location && window.location.href;
if (currentUri) {
baseHeaders.Referer = currentUri;
}
if (params) {
if (!params.headers) {
params.headers = {};
var currentUri = (typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.location && window.location.href;
if (currentUri) {
baseHeaders.Referer = currentUri;
}
params.headers = Object.assign(baseHeaders, params.headers);
} else {
params = { headers: baseHeaders };
}
if (params) {
if (!params.headers) {
params.headers = {};
}
params.headers = this._removeUndefinedHeaders(params.headers);
// eslint-disable-next-line consistent-return
return fetch(input, params).then(function (response) {
if (response.status < 400) {
return response;
params.headers = Object.assign(baseHeaders, params.headers);
} else {
params = { headers: baseHeaders };
}
if (response.status === 401) {
return _this5._manageAccessDenied(response, input, params);
}
params.headers = this._removeUndefinedHeaders(params.headers);
if (response.status !== 401) {
return handleBadResponse(response);
}
});
}
}, {
key: '_removeUndefinedHeaders',
value: function _removeUndefinedHeaders(headers) {
// remove undefined key, usefull to remove Content-Type for example
var localHeaders = headers;
Object.keys(localHeaders).forEach(function (key) {
if (localHeaders[key] === undefined) {
delete localHeaders[key];
}
});
// eslint-disable-next-line consistent-return
return fetch(input, params).then(function (response) {
if (response.status < 400) {
return response;
}
return localHeaders;
}
}, {
key: '_getEntityIdentifier',
value: function _getEntityIdentifier(object) {
return object[this.metadata.getIdentifierAttribute().serializedKey];
}
}]);
return AbstractClient;
}();
if (response.status === 401) {
return _this5._manageAccessDenied(response, input, params);
}
var ACCESS_TOKEN_KEY = 'rest_client_sdk.api.access_token';
if (response.status !== 401) {
return handleBadResponse(response);
}
});
}
}, {
key: '_removeUndefinedHeaders',
value: function _removeUndefinedHeaders(headers) {
// remove undefined key, usefull to remove Content-Type for example
var localHeaders = headers;
Object.keys(localHeaders).forEach(function (key) {
if (localHeaders[key] === undefined) {
delete localHeaders[key];
}
});
var TokenStorage = function () {
function TokenStorage(tokenGenerator, asyncStorage) {
classCallCheck(this, TokenStorage);
return localHeaders;
}
}, {
key: '_getEntityIdentifier',
value: function _getEntityIdentifier(object) {
return object[this.metadata.getIdentifierAttribute().serializedKey];
}
}]);
return AbstractClient;
}();
this._tokenGenerator = tokenGenerator;
this._hasATokenBeenGenerated = false;
this.setAsyncStorage(asyncStorage);
}
var ACCESS_TOKEN_KEY = 'rest_client_sdk.api.access_token';
createClass(TokenStorage, [{
key: 'setAsyncStorage',
value: function setAsyncStorage(asyncStorage) {
this._asyncStorage = asyncStorage;
var TokenStorage = function () {
function TokenStorage(tokenGenerator, asyncStorage) {
classCallCheck(this, TokenStorage);
this._tokenGenerator = tokenGenerator;
this._hasATokenBeenGenerated = false;
this.setAsyncStorage(asyncStorage);
}
}, {
key: 'hasAccessToken',
value: function hasAccessToken() {
return this._asyncStorage.getItem(ACCESS_TOKEN_KEY).then(function (accessToken) {
return !!accessToken;
});
}
}, {
key: 'getAccessToken',
value: function getAccessToken() {
var _this = this;
return this._asyncStorage.getItem(ACCESS_TOKEN_KEY).then(function (token) {
if (!token) {
if (!_this._hasATokenBeenGenerated && !_this._tokenGenerator.canAutogenerateToken) {
throw new Error('No token has been generated yet.');
}
createClass(TokenStorage, [{
key: 'setAsyncStorage',
value: function setAsyncStorage(asyncStorage) {
this._asyncStorage = asyncStorage;
}
}, {
key: 'hasAccessToken',
value: function hasAccessToken() {
return this._asyncStorage.getItem(ACCESS_TOKEN_KEY).then(function (accessToken) {
return !!accessToken;
});
}
}, {
key: 'getAccessToken',
value: function getAccessToken() {
return this.getAccessTokenObject().then(function (token) {
return token && token.access_token;
});
}
}, {
key: 'getAccessTokenObject',
value: function getAccessTokenObject() {
var _this = this;
if (!_this._hasATokenBeenGenerated && _this._tokenGenerator.canAutogenerateToken) {
return _this.generateToken().then(function (generatedToken) {
return generatedToken && generatedToken.access_token;
});
return this._asyncStorage.getItem(ACCESS_TOKEN_KEY).then(function (token) {
if (!token) {
if (!_this._hasATokenBeenGenerated && !_this._tokenGenerator.canAutogenerateToken) {
throw new Error('No token has been generated yet.');
}
if (!_this._hasATokenBeenGenerated && _this._tokenGenerator.canAutogenerateToken) {
return _this.generateToken();
}
}
}
return token && JSON.parse(token).access_token;
});
}
}, {
key: 'logout',
value: function logout() {
return this._asyncStorage.removeItem(ACCESS_TOKEN_KEY);
}
}, {
key: 'generateToken',
value: function generateToken(parameters) {
var _this2 = this;
this._hasATokenBeenGenerated = true;
return this._tokenGenerator.generateToken(parameters).then(function (responseData) {
return _this2._storeAccessToken(responseData).then(function () {
return responseData;
return token && JSON.parse(token);
});
});
}
}, {
key: 'refreshToken',
value: function refreshToken(parameters) {
var _this3 = this;
}
}, {
key: 'logout',
value: function logout() {
return this._asyncStorage.removeItem(ACCESS_TOKEN_KEY);
}
}, {
key: 'generateToken',
value: function generateToken(parameters) {
var _this2 = this;
return this._asyncStorage.getItem(ACCESS_TOKEN_KEY).then(function (token) {
return _this3._tokenGenerator.refreshToken(JSON.parse(token), parameters).then(function (responseData) {
return _this3._storeAccessToken(responseData).then(function () {
this._hasATokenBeenGenerated = true;
return this._tokenGenerator.generateToken(parameters).then(function (responseData) {
return _this2._storeAccessToken(responseData).then(function () {
return responseData;
});
});
});
}
}, {
key: '_storeAccessToken',
value: function _storeAccessToken(responseData) {
return this._asyncStorage.setItem(ACCESS_TOKEN_KEY, JSON.stringify(responseData));
}
}]);
return TokenStorage;
}();
}
}, {
key: 'refreshToken',
value: function refreshToken(parameters) {
var _this3 = this;
/* eslint no-unused-vars: 0 */
return this._asyncStorage.getItem(ACCESS_TOKEN_KEY).then(function (token) {
return _this3._tokenGenerator.refreshToken(JSON.parse(token), parameters).then(function (responseData) {
return _this3._storeAccessToken(responseData).then(function () {
return responseData;
});
});
});
}
}, {
key: '_storeAccessToken',
value: function _storeAccessToken(responseData) {
return this._asyncStorage.setItem(ACCESS_TOKEN_KEY, JSON.stringify(responseData));
}
}]);
return TokenStorage;
}();
var AbstractTokenGenerator = function () {
function AbstractTokenGenerator() {
var tokenGeneratorConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, AbstractTokenGenerator);
/* eslint no-unused-vars: 0 */
this.tokenGeneratorConfig = tokenGeneratorConfig;
this.canAutogenerateToken = false;
this.checkTokenGeneratorConfig(this.tokenGeneratorConfig);
}
var AbstractTokenGenerator = function () {
function AbstractTokenGenerator() {
var tokenGeneratorConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, AbstractTokenGenerator);
createClass(AbstractTokenGenerator, [{
key: "generateToken",
value: function generateToken(parameters) {
throw new Error("AbstractTokenGenerator::generateToken can not be called directly.\n You must implement \"generateToken\" method.");
this.tokenGeneratorConfig = tokenGeneratorConfig;
this.canAutogenerateToken = false;
this.checkTokenGeneratorConfig(this.tokenGeneratorConfig);
}
}, {
key: "refreshToken",
value: function refreshToken(accessToken, parameters) {
throw new Error("AbstractTokenGenerator::refreshToken can not be called directly.\n You must implement \"refreshToken\" method.");
}
}, {
key: "checkTokenGeneratorConfig",
value: function checkTokenGeneratorConfig(config) {
return true;
}
}, {
key: "convertMapToFormData",
value: function convertMapToFormData(parameters) {
var keys = Object.keys(parameters);
var formData = new FormData();
createClass(AbstractTokenGenerator, [{
key: "generateToken",
value: function generateToken(parameters) {
throw new Error("AbstractTokenGenerator::generateToken can not be called directly.\n You must implement \"generateToken\" method.");
}
}, {
key: "refreshToken",
value: function refreshToken(accessToken, parameters) {
throw new Error("AbstractTokenGenerator::refreshToken can not be called directly.\n You must implement \"refreshToken\" method.");
}
}, {
key: "checkTokenGeneratorConfig",
value: function checkTokenGeneratorConfig(config) {
return true;
}
}, {
key: "convertMapToFormData",
value: function convertMapToFormData(parameters) {
var keys = Object.keys(parameters);
keys.forEach(function (key) {
formData.append(key, parameters[key]);
});
var formData = new FormData();
return formData;
}
}]);
return AbstractTokenGenerator;
}();
keys.forEach(function (key) {
formData.append(key, parameters[key]);
});
/* eslint import/prefer-default-export: 0 */
return formData;
}
}]);
return AbstractTokenGenerator;
}();
// memoize promise returning function so that it returns
// the same promise if called again before resolve / reject
function memoizePromise(callback) {
var cache = {};
function memoized() {
for (var _len = arguments.length, parameters = Array(_len), _key = 0; _key < _len; _key++) {
parameters[_key] = arguments[_key];
}
/* eslint import/prefer-default-export: 0 */
var cacheKey = JSON.stringify(parameters);
// memoize promise returning function so that it returns
// the same promise if called again before resolve / reject
function memoizePromise(callback) {
var cache = {};
function memoized() {
for (var _len = arguments.length, parameters = Array(_len), _key = 0; _key < _len; _key++) {
parameters[_key] = arguments[_key];
}
if (cache[cacheKey]) {
return cache[cacheKey];
}
var cacheKey = JSON.stringify(parameters);
// Get and add the value to the cache
var value = callback.apply(this, parameters);
cache[cacheKey] = value;
if (cache[cacheKey]) {
return cache[cacheKey];
}
var isPromise = !!value && typeof value.then === 'function';
if (!isPromise) {
throw new Error('Memoization Error, Async function returned non-promise value');
// Get and add the value to the cache
var value = callback.apply(this, parameters);
cache[cacheKey] = value;
var isPromise = !!value && typeof value.then === 'function';
if (!isPromise) {
throw new Error('Memoization Error, Async function returned non-promise value');
}
// Delete the value regardless of whether it resolves or rejects
return value.then(function (internalValue) {
cache[cacheKey] = false;
return internalValue;
}, function (err) {
cache[cacheKey] = false;
throw err;
});
}
// Delete the value regardless of whether it resolves or rejects
return value.then(function (internalValue) {
cache[cacheKey] = false;
return internalValue;
}, function (err) {
cache[cacheKey] = false;
throw err;
});
memoized.cache = cache;
return memoized;
}
memoized.cache = cache;
return memoized;
}
var ERROR_CONFIG_EMPTY = 'TokenGenerator config must be set';
var ERROR_CONFIG_PATH_SCHEME = 'TokenGenerator config is not valid, it should contain a "path", a "scheme" parameter';
var ERROR_CONFIG_CLIENT_INFORMATIONS = 'TokenGenerator config is not valid, it should contain a "clientId", a "clientSecret" parameter';
var ERROR_CONFIG_EMPTY = 'TokenGenerator config must be set';
var ERROR_CONFIG_PATH_SCHEME = 'TokenGenerator config is not valid, it should contain a "path", a "scheme" parameter';
var ERROR_CONFIG_CLIENT_INFORMATIONS = 'TokenGenerator config is not valid, it should contain a "clientId", a "clientSecret" parameter';
var ClientCredentialsGenerator = function (_AbstractTokenGenerat) {
inherits(ClientCredentialsGenerator, _AbstractTokenGenerat);
var ClientCredentialsGenerator = function (_AbstractTokenGenerat) {
inherits(ClientCredentialsGenerator, _AbstractTokenGenerat);
function ClientCredentialsGenerator(props) {
classCallCheck(this, ClientCredentialsGenerator);
function ClientCredentialsGenerator(props) {
classCallCheck(this, ClientCredentialsGenerator);
var _this = possibleConstructorReturn(this, (ClientCredentialsGenerator.__proto__ || Object.getPrototypeOf(ClientCredentialsGenerator)).call(this, props));
var _this = possibleConstructorReturn(this, (ClientCredentialsGenerator.__proto__ || Object.getPrototypeOf(ClientCredentialsGenerator)).call(this, props));
_this.generateToken = memoizePromise(_this.generateToken);
return _this;
}
_this.generateToken = memoizePromise(_this.generateToken);
return _this;
}
createClass(ClientCredentialsGenerator, [{
key: 'generateToken',
value: function generateToken() {
var baseParameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
createClass(ClientCredentialsGenerator, [{
key: 'generateToken',
value: function generateToken() {
var baseParameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var parameters = baseParameters;
parameters.grant_type = 'client_credentials';
parameters.client_id = this.tokenGeneratorConfig.clientId;
parameters.client_secret = this.tokenGeneratorConfig.clientSecret;
var parameters = baseParameters;
parameters.grant_type = 'client_credentials';
parameters.client_id = this.tokenGeneratorConfig.clientId;
parameters.client_secret = this.tokenGeneratorConfig.clientSecret;
if (this.tokenGeneratorConfig.scope && !parameters.scope) {
parameters.scope = this.tokenGeneratorConfig.scope;
}
if (this.tokenGeneratorConfig.scope && !parameters.scope) {
parameters.scope = this.tokenGeneratorConfig.scope;
}
var uri = new URI(this.tokenGeneratorConfig.path).scheme(this.tokenGeneratorConfig.scheme);
var uri = new URI(this.tokenGeneratorConfig.path).scheme(this.tokenGeneratorConfig.scheme);
if (this.tokenGeneratorConfig.port) {
uri.port(this.tokenGeneratorConfig.port);
}
if (this.tokenGeneratorConfig.port) {
uri.port(this.tokenGeneratorConfig.port);
}
var url = uri.toString();
var url = uri.toString();
return fetch(url, {
method: 'POST',
body: this.convertMapToFormData(parameters)
}).then(function (response) {
if (response.status !== 200) {
return handleBadResponse(response);
}
return fetch(url, {
method: 'POST',
body: this.convertMapToFormData(parameters)
}).then(function (response) {
if (response.status !== 200) {
return handleBadResponse(response);
return response.json();
});
}
}, {
key: 'refreshToken',
value: function refreshToken(accessToken, parameters) {
return this.generateToken(parameters);
}
}, {
key: 'checkTokenGeneratorConfig',
value: function checkTokenGeneratorConfig(config) {
if (!config || Object.keys(config).length === 0) {
throw new RangeError(ERROR_CONFIG_EMPTY);
}
return response.json();
});
}
}, {
key: 'refreshToken',
value: function refreshToken(accessToken, parameters) {
return this.generateToken(parameters);
}
}, {
key: 'checkTokenGeneratorConfig',
value: function checkTokenGeneratorConfig(config) {
if (!config || Object.keys(config).length === 0) {
throw new RangeError(ERROR_CONFIG_EMPTY);
}
if (!(config.path && config.scheme)) {
throw new RangeError(ERROR_CONFIG_PATH_SCHEME);
}
if (!(config.path && config.scheme)) {
throw new RangeError(ERROR_CONFIG_PATH_SCHEME);
if (!(config.clientId && config.clientSecret)) {
throw new RangeError(ERROR_CONFIG_CLIENT_INFORMATIONS);
}
}
}]);
return ClientCredentialsGenerator;
}(AbstractTokenGenerator);
if (!(config.clientId && config.clientSecret)) {
throw new RangeError(ERROR_CONFIG_CLIENT_INFORMATIONS);
}
}
}]);
return ClientCredentialsGenerator;
}(AbstractTokenGenerator);
var ERROR_CONFIG_EMPTY$1 = 'TokenGenerator config must be set';
var ERROR_CONFIG_PATH_SCHEME$1 = 'TokenGenerator config is not valid, it should contain a "path", a "scheme" parameter';
var ERROR_CONFIG_CLIENT_INFORMATIONS$1 = 'TokenGenerator config is not valid, it should contain a "clientId", a "clientSecret" parameter';
var ERROR_CONFIG_EMPTY$1 = 'TokenGenerator config must be set';
var ERROR_CONFIG_PATH_SCHEME$1 = 'TokenGenerator config is not valid, it should contain a "path", a "scheme" parameter';
var ERROR_CONFIG_CLIENT_INFORMATIONS$1 = 'TokenGenerator config is not valid, it should contain a "clientId", a "clientSecret" parameter';
var ERROR_TOKEN_EMPTY = 'parameters must be set';
var ERROR_TOKEN_USERNAME_PASSWORD = 'username and password must be passed as parameters';
var ERROR_TOKEN_EMPTY = 'parameters must be set';
var ERROR_TOKEN_USERNAME_PASSWORD = 'username and password must be passed as parameters';
var PasswordGenerator = function (_AbstractTokenGenerat) {
inherits(PasswordGenerator, _AbstractTokenGenerat);
var PasswordGenerator = function (_AbstractTokenGenerat) {
inherits(PasswordGenerator, _AbstractTokenGenerat);
function PasswordGenerator(props) {
classCallCheck(this, PasswordGenerator);
function PasswordGenerator(props) {
classCallCheck(this, PasswordGenerator);
var _this = possibleConstructorReturn(this, (PasswordGenerator.__proto__ || Object.getPrototypeOf(PasswordGenerator)).call(this, props));
var _this = possibleConstructorReturn(this, (PasswordGenerator.__proto__ || Object.getPrototypeOf(PasswordGenerator)).call(this, props));
_this._doFetch = memoizePromise(_this._doFetch);
return _this;
}
_this._doFetch = memoizePromise(_this._doFetch);
return _this;
}
createClass(PasswordGenerator, [{
key: 'generateToken',
value: function generateToken(baseParameters) {
var parameters = baseParameters;
this._checkGenerateParameters(parameters);
createClass(PasswordGenerator, [{
key: 'generateToken',
value: function generateToken(baseParameters) {
var parameters = baseParameters;
this._checkGenerateParameters(parameters);
parameters.grant_type = 'password';
parameters.client_id = this.tokenGeneratorConfig.clientId;
parameters.client_secret = this.tokenGeneratorConfig.clientSecret;
parameters.grant_type = 'password';
parameters.client_id = this.tokenGeneratorConfig.clientId;
parameters.client_secret = this.tokenGeneratorConfig.clientSecret;
if (this.tokenGeneratorConfig.scope && !parameters.scope) {
parameters.scope = this.tokenGeneratorConfig.scope;
}
if (this.tokenGeneratorConfig.scope && !parameters.scope) {
parameters.scope = this.tokenGeneratorConfig.scope;
return this._doFetch(parameters).then(function (response) {
return response.json();
});
}
}, {
key: 'refreshToken',
value: function refreshToken(accessToken) {
var baseParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this._doFetch(parameters).then(function (response) {
return response.json();
});
}
}, {
key: 'refreshToken',
value: function refreshToken(accessToken) {
var baseParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!(accessToken && accessToken.refresh_token)) {
throw new Error('refresh_token is not set. Did you called `generateToken` before ?');
}
if (!(accessToken && accessToken.refresh_token)) {
throw new Error('refresh_token is not set. Did you called `generateToken` before ?');
}
var parameters = baseParameters;
var parameters = baseParameters;
parameters.grant_type = 'refresh_token';
parameters.client_id = this.tokenGeneratorConfig.clientId;
parameters.client_secret = this.tokenGeneratorConfig.clientSecret;
if (this.tokenGeneratorConfig.scope && !parameters.scope) {
parameters.scope = this.tokenGeneratorConfig.scope;
}
parameters.grant_type = 'refresh_token';
parameters.client_id = this.tokenGeneratorConfig.clientId;
parameters.client_secret = this.tokenGeneratorConfig.clientSecret;
if (this.tokenGeneratorConfig.scope && !parameters.scope) {
parameters.scope = this.tokenGeneratorConfig.scope;
parameters.refresh_token = accessToken.refresh_token;
return this._doFetch(parameters).then(function (response) {
return response.clone().json();
}).catch(function (err) {
if (err instanceof BadRequestError) {
throw new AccessDeniedError(err.message, err.baseResponse);
}
throw err;
});
}
}, {
key: 'checkTokenGeneratorConfig',
value: function checkTokenGeneratorConfig(config) {
if (!config || Object.keys(config).length === 0) {
throw new RangeError(ERROR_CONFIG_EMPTY$1);
}
parameters.refresh_token = accessToken.refresh_token;
if (!(config.path && config.scheme)) {
throw new RangeError(ERROR_CONFIG_PATH_SCHEME$1);
}
return this._doFetch(parameters).then(function (response) {
return response.clone().json();
}).catch(function (err) {
if (err instanceof BadRequestError) {
throw new AccessDeniedError(err.message, err.baseResponse);
if (!(config.clientId && config.clientSecret)) {
throw new RangeError(ERROR_CONFIG_CLIENT_INFORMATIONS$1);
}
throw err;
});
}
}, {
key: 'checkTokenGeneratorConfig',
value: function checkTokenGeneratorConfig(config) {
if (!config || Object.keys(config).length === 0) {
throw new RangeError(ERROR_CONFIG_EMPTY$1);
}
}, {
key: '_doFetch',
value: function _doFetch(parameters) {
var uri = new URI(this.tokenGeneratorConfig.path);
uri.scheme(this.tokenGeneratorConfig.scheme);
if (!(config.path && config.scheme)) {
throw new RangeError(ERROR_CONFIG_PATH_SCHEME$1);
}
if (this.tokenGeneratorConfig.port) {
uri.port(this.tokenGeneratorConfig.port);
}
if (!(config.clientId && config.clientSecret)) {
throw new RangeError(ERROR_CONFIG_CLIENT_INFORMATIONS$1);
}
}
}, {
key: '_doFetch',
value: function _doFetch(parameters) {
var uri = new URI(this.tokenGeneratorConfig.path);
uri.scheme(this.tokenGeneratorConfig.scheme);
var url = uri.toString();
if (this.tokenGeneratorConfig.port) {
uri.port(this.tokenGeneratorConfig.port);
return fetch(url, {
method: 'POST',
body: this.convertMapToFormData(parameters)
}).then(function (response) {
if (response.status >= 400) {
handleBadResponse(response);
}
return response;
});
}
}, {
key: '_checkGenerateParameters',
value: function _checkGenerateParameters(parameters) {
if (!(parameters && Object.keys(parameters).length > 0)) {
throw new RangeError(ERROR_TOKEN_EMPTY);
}
var url = uri.toString();
return fetch(url, {
method: 'POST',
body: this.convertMapToFormData(parameters)
}).then(function (response) {
if (response.status >= 400) {
handleBadResponse(response);
if (!(parameters.username && parameters.password)) {
throw new RangeError(ERROR_TOKEN_USERNAME_PASSWORD);
}
return response;
});
}
}, {
key: '_checkGenerateParameters',
value: function _checkGenerateParameters(parameters) {
if (!(parameters && Object.keys(parameters).length > 0)) {
throw new RangeError(ERROR_TOKEN_EMPTY);
}
}]);
return PasswordGenerator;
}(AbstractTokenGenerator);
if (!(parameters.username && parameters.password)) {
throw new RangeError(ERROR_TOKEN_USERNAME_PASSWORD);
}
}
}]);
return PasswordGenerator;
}(AbstractTokenGenerator);
var ProvidedTokenGenerator = function (_AbstractTokenGenerat) {
inherits(ProvidedTokenGenerator, _AbstractTokenGenerat);
var ProvidedTokenGenerator = function (_AbstractTokenGenerat) {
inherits(ProvidedTokenGenerator, _AbstractTokenGenerat);
function ProvidedTokenGenerator(token) {
var refreshTokenFunc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
classCallCheck(this, ProvidedTokenGenerator);
function ProvidedTokenGenerator(token) {
var refreshTokenFunc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
classCallCheck(this, ProvidedTokenGenerator);
var _this = possibleConstructorReturn(this, (ProvidedTokenGenerator.__proto__ || Object.getPrototypeOf(ProvidedTokenGenerator)).call(this));
var _this = possibleConstructorReturn(this, (ProvidedTokenGenerator.__proto__ || Object.getPrototypeOf(ProvidedTokenGenerator)).call(this));
_this._token = token;
_this.canAutogenerateToken = true;
_this._refreshTokenFunc = refreshTokenFunc;
return _this;
}
_this._token = token;
_this.canAutogenerateToken = true;
_this._refreshTokenFunc = refreshTokenFunc;
return _this;
}
createClass(ProvidedTokenGenerator, [{
key: 'generateToken',
value: function generateToken() {
return Promise.resolve({
access_token: this._token
});
}
}, {
key: 'refreshToken',
value: function refreshToken() {
if (typeof this._refreshTokenFunc === 'function') {
return this._refreshTokenFunc();
}
createClass(ProvidedTokenGenerator, [{
key: 'generateToken',
value: function generateToken() {
return Promise.resolve({
access_token: this._token
});
}
}, {
key: 'refreshToken',
value: function refreshToken() {
if (typeof this._refreshTokenFunc === 'function') {
return this._refreshTokenFunc();
return this.generateToken();
}
}]);
return ProvidedTokenGenerator;
}(AbstractTokenGenerator);
return this.generateToken();
var Attribute = function Attribute(serializedKey) {
var attributeName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'string';
var isIdentifier = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
classCallCheck(this, Attribute);
if (!serializedKey) {
throw new TypeError('`serializedKey` must not be empty');
}
}]);
return ProvidedTokenGenerator;
}(AbstractTokenGenerator);
var Attribute = function Attribute(serializedKey) {
var attributeName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'string';
var isIdentifier = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
classCallCheck(this, Attribute);
this.serializedKey = serializedKey;
this.attributeName = attributeName || this.serializedKey;
this.type = type;
this.isIdentifier = isIdentifier;
};
if (!serializedKey) {
throw new TypeError('`serializedKey` must not be empty');
}
var ClassMetadata = function () {
function ClassMetadata(key) {
var pathRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var repositoryClass = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
classCallCheck(this, ClassMetadata);
this.serializedKey = serializedKey;
this.attributeName = attributeName || this.serializedKey;
this.type = type;
this.isIdentifier = isIdentifier;
};
if (!key) {
throw new TypeError('key attribute are required');
}
var ClassMetadata = function () {
function ClassMetadata(key) {
var pathRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var repositoryClass = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
classCallCheck(this, ClassMetadata);
this.key = key;
this.pathRoot = pathRoot || key;
// this.modelName = modelName;
this.repositoryClass = repositoryClass || AbstractClient;
if (!key) {
throw new TypeError('key attribute are required');
this._attributeList = {};
this._relationList = {};
this._identifierAttribute = null;
}
this.key = key;
this.pathRoot = pathRoot || key;
// this.modelName = modelName;
this.repositoryClass = repositoryClass || AbstractClient;
createClass(ClassMetadata, [{
key: 'getAttribute',
value: function getAttribute(name) {
return this._attributeList[name];
}
}, {
key: 'getIdentifierAttribute',
value: function getIdentifierAttribute() {
return this._identifierAttribute;
}
}, {
key: 'getAttributeList',
value: function getAttributeList() {
return this._attributeList;
}
}, {
key: 'setAttributeList',
value: function setAttributeList(attributeList) {
var _this = this;
this._attributeList = {};
this._relationList = {};
this._identifierAttribute = null;
}
this._attributeList = {};
this._identifierAttribute = null;
createClass(ClassMetadata, [{
key: 'getAttribute',
value: function getAttribute(name) {
return this._attributeList[name];
}
}, {
key: 'getIdentifierAttribute',
value: function getIdentifierAttribute() {
return this._identifierAttribute;
}
}, {
key: 'getAttributeList',
value: function getAttributeList() {
return this._attributeList;
}
}, {
key: 'setAttributeList',
value: function setAttributeList(attributeList) {
var _this = this;
attributeList.forEach(function (attribute) {
_this._attributeList[attribute.serializedKey] = attribute;
this._attributeList = {};
this._identifierAttribute = null;
if (attribute.isIdentifier) {
_this._identifierAttribute = attribute;
}
});
attributeList.forEach(function (attribute) {
_this._attributeList[attribute.serializedKey] = attribute;
if (attribute.isIdentifier) {
_this._identifierAttribute = attribute;
if (!this._identifierAttribute) {
throw new TypeError('"' + this.key + '" has no identifier attribute set. You must set all your attributes in one time and send an attribute with "isIdentifier=true"');
}
});
}
}, {
key: 'setRelationList',
value: function setRelationList(relationList) {
var _this2 = this;
if (!this._identifierAttribute) {
throw new TypeError('"' + this.key + '" has no identifier attribute set. You must set all your attributes in one time and send an attribute with "isIdentifier=true"');
this._relationList = {};
relationList.forEach(function (relation) {
_this2._relationList[relation.serializedKey] = relation;
_this2._attributeList[relation.serializedKey] = new Attribute(relation.serializedKey, relation.serializedKey, relation.isOneToMany() ? 'array' : 'object');
});
}
}
}, {
key: 'setRelationList',
value: function setRelationList(relationList) {
var _this2 = this;
}, {
key: 'getRelation',
value: function getRelation(key) {
return this._relationList[key];
}
}, {
key: 'getDefaultSerializedModel',
value: function getDefaultSerializedModel() {
var _this3 = this;
this._relationList = {};
var out = {};
relationList.forEach(function (relation) {
_this2._relationList[relation.serializedKey] = relation;
_this2._attributeList[relation.serializedKey] = new Attribute(relation.serializedKey, relation.serializedKey, relation.isOneToMany() ? 'array' : 'object');
});
}
}, {
key: 'getRelation',
value: function getRelation(key) {
return this._relationList[key];
}
}, {
key: 'getDefaultSerializedModel',
value: function getDefaultSerializedModel() {
var _this3 = this;
Object.keys(this._attributeList).forEach(function (serializedKey) {
out[serializedKey] = null;
});
var out = {};
Object.keys(this._relationList).forEach(function (serializedKey) {
var relation = _this3._relationList[serializedKey];
Object.keys(this._attributeList).forEach(function (serializedKey) {
out[serializedKey] = null;
});
if (relation.isOneToMany()) {
out[serializedKey] = [];
}
});
Object.keys(this._relationList).forEach(function (serializedKey) {
var relation = _this3._relationList[serializedKey];
return out;
}
}]);
return ClassMetadata;
}();
if (relation.isOneToMany()) {
out[serializedKey] = [];
}
});
var Relation = function () {
function Relation(type, targetMetadataKey, serializedKey) {
var attributeName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
classCallCheck(this, Relation);
return out;
this.type = type;
this.targetMetadataKey = targetMetadataKey;
this.serializedKey = serializedKey;
this.attributeName = attributeName || this.serializedKey;
}
}]);
return ClassMetadata;
}();
var Relation = function () {
function Relation(type, targetMetadataKey, serializedKey) {
var attributeName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
classCallCheck(this, Relation);
createClass(Relation, [{
key: 'isOneToMany',
value: function isOneToMany() {
return this.type === Relation.ONE_TO_MANY;
}
}, {
key: 'isManyToOne',
value: function isManyToOne() {
return this.type === Relation.MANY_TO_ONE;
}
}]);
return Relation;
}();
this.type = type;
this.targetMetadataKey = targetMetadataKey;
this.serializedKey = serializedKey;
this.attributeName = attributeName || this.serializedKey;
}
Relation.ONE_TO_MANY = 'ONE_TO_MANY';
Relation.MANY_TO_ONE = 'MANY_TO_ONE';
createClass(Relation, [{
key: 'isOneToMany',
value: function isOneToMany() {
return this.type === Relation.ONE_TO_MANY;
}
}, {
key: 'isManyToOne',
value: function isManyToOne() {
return this.type === Relation.MANY_TO_ONE;
}
}]);
return Relation;
}();
exports.default = RestClientSdk;
exports.AbstractClient = AbstractClient;
exports.AbstractTokenGenerator = AbstractTokenGenerator;
exports.ClientCredentialsGenerator = ClientCredentialsGenerator;
exports.PasswordGenerator = PasswordGenerator;
exports.ProvidedTokenGenerator = ProvidedTokenGenerator;
exports.Serializer = Serializer;
exports.TokenStorage = TokenStorage;
exports.AccessDeniedError = AccessDeniedError;
exports.BadRequestError = BadRequestError;
exports.ForbiddenError = ForbiddenError;
exports.HttpError = HttpError;
exports.InternalServerError = InternalServerError;
exports.ResourceNotFoundError = ResourceNotFoundError;
exports.Mapping = Mapping;
exports.ClassMetadata = ClassMetadata;
exports.Attribute = Attribute;
exports.Relation = Relation;
Relation.ONE_TO_MANY = 'ONE_TO_MANY';
Relation.MANY_TO_ONE = 'MANY_TO_ONE';
Object.defineProperty(exports, '__esModule', { value: true });
exports['default'] = RestClientSdk;
exports.AbstractClient = AbstractClient;
exports.AbstractTokenGenerator = AbstractTokenGenerator;
exports.ClientCredentialsGenerator = ClientCredentialsGenerator;
exports.PasswordGenerator = PasswordGenerator;
exports.ProvidedTokenGenerator = ProvidedTokenGenerator;
exports.Serializer = Serializer;
exports.TokenStorage = TokenStorage;
exports.AccessDeniedError = AccessDeniedError;
exports.BadRequestError = BadRequestError;
exports.ForbiddenError = ForbiddenError;
exports.HttpError = HttpError;
exports.InternalServerError = InternalServerError;
exports.ResourceNotFoundError = ResourceNotFoundError;
exports.Mapping = Mapping;
exports.ClassMetadata = ClassMetadata;
exports.Attribute = Attribute;
exports.Relation = Relation;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=index.js.map
{
"name": "rest-client-sdk",
"version": "v2.0.1",
"version": "v2.1.0",
"description": "Rest Client SDK for API",

@@ -26,3 +26,3 @@ "main": "dist/index.js",

"babel-preset-env": "^1.6.1",
"bundlesize": "^0.15.3",
"bundlesize": "^0.17.0",
"eslint": "^4.15.0",

@@ -40,9 +40,9 @@ "eslint-config-airbnb": "^16.1.0",

"jest": "^22.1.1",
"lint-staged": "^6.0.0",
"lint-staged": "^7.0.3",
"pluralize": "^7.0.0",
"prettier": "^1.10.2",
"rimraf": "^2.6.2",
"rollup": "^0.54.0",
"rollup": "^0.57.1",
"rollup-plugin-babel": "^3.0.3",
"rollup-plugin-commonjs": "^8.2.6",
"rollup-plugin-commonjs": "^9.1.0",
"rollup-plugin-node-resolve": "^3.0.0"

@@ -74,3 +74,3 @@ },

"lint-staged": {
"*.{js,jsx,json,md}": ["prettier --write", "git add"]
"*.{js,jsx,json,md}": ["yarn run prettier --write", "git add"]
},

@@ -77,0 +77,0 @@ "jest": {

@@ -21,2 +21,8 @@ const ACCESS_TOKEN_KEY = 'rest_client_sdk.api.access_token';

getAccessToken() {
return this.getAccessTokenObject().then(
token => token && token.access_token
);
}
getAccessTokenObject() {
return this._asyncStorage.getItem(ACCESS_TOKEN_KEY).then(token => {

@@ -35,9 +41,7 @@ if (!token) {

) {
return this.generateToken().then(
generatedToken => generatedToken && generatedToken.access_token
);
return this.generateToken();
}
}
return token && JSON.parse(token).access_token;
return token && JSON.parse(token);
});

@@ -44,0 +48,0 @@ }

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc