d2-ui
Version:
190 lines (161 loc) • 7.84 kB
JavaScript
Object.defineProperty(exports, '__esModule', {
value: true
});
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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _ModelValidation = require('./ModelValidation');
var _ModelValidation2 = _interopRequireDefault(_ModelValidation);
var _libCheck = require('../lib/check');
var modelValidator = _ModelValidation2['default'].getModelValidation();
var DIRTY_PROPERTY_LIST = Symbol('List to keep track of dirty properties');
exports.DIRTY_PROPERTY_LIST = DIRTY_PROPERTY_LIST;
function hasModelValidationForProperty(model, property) {
return Boolean(model.modelDefinition && model.modelDefinition.modelValidations && model.modelDefinition.modelValidations[property] && Object.prototype.hasOwnProperty.call(model.modelDefinition.modelValidations, property));
}
/**
* @class ModelBase
*/
var ModelBase = (function () {
function ModelBase() {
_classCallCheck(this, ModelBase);
}
_createClass(ModelBase, [{
key: 'save',
/**
* @method save
*
* @returns {Promise} Returns a promise that resolves when the model has been saved
* or rejects with the result from the `validate()` call.
*
* @description
* Checks if the model is dirty. When the model is dirty it will check if the values of the model are valid by calling
* `validate`. If this is correct it will attempt to save the [Model](#/model/Model) to the api.
*
* ```js
* myModel.save()
* .then((message) => console.log(message));
* ```
*/
value: function save() {
var _this = this;
var includeChildren = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
if (!(this.dirty || includeChildren === true && this.hasDirtyChildren())) {
return Promise.reject('No changes to be saved');
}
return this.validate().then(function (validationState) {
if (!validationState.status) {
return Promise.reject(validationState);
}
return _this.modelDefinition.save(_this).then(function (result) {
if (result && result.response.importCount.imported === 1 && (0, _libCheck.isValidUid)(result.response.lastImported)) {
_this.dataValues.id = result.response.lastImported;
_this.dataValues.href = [_this.modelDefinition.apiEndpoint, _this.dataValues.id].join('/');
}
_this.dirty = false;
_this.getDirtyChildren().forEach(function (value) {
value.dirty = false; // eslint-disable-line no-param-reassign
});
_this[DIRTY_PROPERTY_LIST].clear();
return result;
});
});
}
/**
* @method validate
*
* @returns {Promise} Promise that resolves with an object with a status property that represents if the model
* is valid or not the fields array will return the names of the fields that are invalid.
*
* @description
* This will run the validations on the properties which have validations set. Normally these validations are defined
* through the DHIS2 schema. It will check min/max for strings/numbers etc. Additionally it will
* run model validations against the schema.
*
* ```js
* myModel.validate()
* .then(myModelStatus => {
* if (myModelStatus.status === false) {
* myModelStatus.fields.forEach((fieldName) => console.log(fieldName));
* }
* });
* ```
*/
}, {
key: 'validate',
value: function validate() {
var _this2 = this;
return new Promise(function (resolve, reject) {
var validationMessages = [];
function unique(current, property) {
if (property && current.indexOf(property) === -1) {
current.push(property);
}
return current;
}
function asyncRemoteValidation(model) {
return modelValidator.validateAgainstSchema(model);
}
// Run async validation against the api
asyncRemoteValidation(_this2).then(function (remoteMessages) {
validationMessages = validationMessages.concat(remoteMessages);
var validationState = {
status: remoteMessages.length === 0,
fields: validationMessages.map(function (validationMessage) {
return validationMessage.property;
}).reduce(unique, []),
messages: validationMessages
};
resolve(validationState);
})['catch'](function (message) {
return reject(message);
});
});
}
}, {
key: 'delete',
value: function _delete() {
return this.modelDefinition['delete'](this);
}
}, {
key: 'getDirtyPropertyNames',
value: function getDirtyPropertyNames() {
return Array.from(this[DIRTY_PROPERTY_LIST].values());
}
}, {
key: 'getCollectionChildren',
value: function getCollectionChildren() {
var _this3 = this;
// TODO: Can't be sure that this has a `modelDefinition` property
return Object.keys(this).filter(function (propertyName) {
return _this3[propertyName] && hasModelValidationForProperty(_this3, propertyName) && _this3.modelDefinition.modelValidations[propertyName].owner && _this3[propertyName].size >= 0;
}).map(function (propertyName) {
return _this3[propertyName];
});
}
}, {
key: 'getCollectionChildrenPropertyNames',
value: function getCollectionChildrenPropertyNames() {
var _this4 = this;
return Object.keys(this).filter(function (propertyName) {
return _this4.modelDefinition && _this4.modelDefinition.modelValidations && _this4.modelDefinition.modelValidations[propertyName] && _this4.modelDefinition.modelValidations[propertyName].type === 'COLLECTION';
});
}
}, {
key: 'getDirtyChildren',
value: function getDirtyChildren() {
return this.getCollectionChildren().filter(function (property) {
return property && property.dirty === true;
});
}
}, {
key: 'hasDirtyChildren',
value: function hasDirtyChildren() {
return this.getDirtyChildren().length > 0;
}
}]);
return ModelBase;
})();
exports['default'] = new ModelBase();
//# sourceMappingURL=ModelBase.js.map
;