UNPKG

d2-ui

Version:
241 lines (207 loc) 9.48 kB
'use strict'; 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 _helpersJson = require('./helpers/json'); 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)); } function updateModelFromResponseStatus(result) { if (result && result.httpStatus === 'Created' && result && (0, _libCheck.isValidUid)(result.response.uid)) { this.dataValues.id = result.response.uid; this.dataValues.href = [this.modelDefinition.apiEndpoint, this.dataValues.id].join('/'); } this.dirty = false; this.getDirtyChildren().forEach(function (value) { if (value.resetDirtyState) { value.resetDirtyState(); } else { value.dirty = false; // eslint-disable-line no-param-reassign } }); this[DIRTY_PROPERTY_LIST].clear(); return result; } /** * @class ModelBase */ var ModelBase = (function () { function ModelBase() { _classCallCheck(this, ModelBase); } _createClass(ModelBase, [{ key: 'create', /** * @method create * * @returns {Promise} Returns a promise that resolves when the model has been saved or rejected with the result from * the `validate()` call. * * @definition * Will save model as a new object to the server using a POST request. This method would generally be used if * you're creating models with pre-specified IDs. Note that this does not check if the model is marked as dirty. */ value: function create() { var _this = this; return this.validate().then(function (validationState) { if (!validationState.status) { return Promise.reject(validationState); } return _this.modelDefinition.saveNew(_this).then(updateModelFromResponseStatus.bind(_this)); }); } /** * @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)); * ``` */ }, { key: 'save', value: function save(includeChildren) { var _this2 = this; if (!this.isDirty(includeChildren)) { return Promise.reject('No changes to be saved'); } return this.validate().then(function (validationState) { if (!validationState.status) { return Promise.reject(validationState); } return _this2.modelDefinition.save(_this2).then(updateModelFromResponseStatus.bind(_this2)); }); } /** * @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 _this3 = 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(_this3)['catch'](function (remoteMessages) { // Errors are ok in this case if (Array.isArray(remoteMessages)) { return remoteMessages; } return Promise.reject(remoteMessages); }).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: 'clone', value: function clone() { return this.modelDefinition.create((0, _helpersJson.getJSONForProperties)(this, Object.keys(this.modelDefinition.modelValidations))); } }, { key: 'delete', value: function _delete() { return this.modelDefinition['delete'](this); } }, { key: 'isDirty', value: function isDirty() { var includeChildren = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; if (!(this.dirty || includeChildren === true && this.hasDirtyChildren())) { return false; } return true; } }, { key: 'getDirtyPropertyNames', value: function getDirtyPropertyNames() { return Array.from(this[DIRTY_PROPERTY_LIST].values()); } }, { key: 'getCollectionChildren', value: function getCollectionChildren() { var _this4 = this; // TODO: Can't be sure that this has a `modelDefinition` property return Object.keys(this).filter(function (propertyName) { return _this4[propertyName] && hasModelValidationForProperty(_this4, propertyName) && _this4.modelDefinition.modelValidations[propertyName].owner; }).map(function (propertyName) { return _this4[propertyName]; }); } }, { key: 'getCollectionChildrenPropertyNames', value: function getCollectionChildrenPropertyNames() { var _this5 = this; return Object.keys(this).filter(function (propertyName) { return _this5.modelDefinition && _this5.modelDefinition.modelValidations && _this5.modelDefinition.modelValidations[propertyName] && _this5.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