UNPKG

nm-viewmodel

Version:

core api for low code paltform

813 lines (783 loc) 26.3 kB
'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var uuid = require('uuid'); var axios = _interopDefault(require('axios')); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var BaseModel = /** @class */ (function () { function BaseModel() { this.data = {}; this.updateProps = []; this.uuid = ''; } return BaseModel; }()); var EventModel = /** @class */ (function (_super) { __extends(EventModel, _super); function EventModel() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.events = {}; _this.listeners = []; return _this; } // 事件监听 EventModel.prototype.on = function (method, callback, context) { var event = this.events[method] || (this.events[method] = []); event.push({ callback: callback, context: context }); }; // 事件触发 EventModel.prototype.emit = function (method) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (!method) return; var events = this.events[method]; var returnData; if (events) { events.forEach(function (event) { try { if (event) { var returnResult = event.callback.apply(event.context, rest); if (returnResult != undefined) { returnData = returnResult; } } } catch (e) { console.error('execute[' + method + '] exception: ' + e.stack); } }); } else { return true; } return returnData; }; EventModel.prototype.off = function (method, callback) { var events = this.events; if (!method || !events || !events[method]) return; if (!callback) { delete events[method]; } else { var index = events[method].findIndex(function (value) { if (value.callback === callback) return true; }); if (index !== -1) events[method].splice(index, 1); } }; EventModel.prototype.addListener = function (listener) { if (this.listeners.indexOf(listener) < 0) { this.listeners.push(listener); } }; EventModel.prototype.updateLisener = function (datas) { this.listeners.forEach(function (fn) { fn && fn(datas); }); }; EventModel.prototype.removeListener = function (listener) { var index; if ((index = this.listeners.indexOf(listener)) >= 0) { this.listeners.splice(index, 1); } }; return EventModel; }(BaseModel)); var BizModel = /** @class */ (function (_super) { __extends(BizModel, _super); function BizModel(obj) { var _this = _super.call(this) || this; _this.modelType = 'bizmodel'; var props = []; if (obj) { props = Object.keys(obj); } _this.updateProps = []; _this.data = Object.assign({ props: props }, obj); return _this; } BizModel.prototype.get = function (key) { if (!key) return; return this.data[key]; }; BizModel.prototype.getData = function () { return this.data; }; BizModel.prototype.getInstance = function () { return this; }; BizModel.prototype.set = function (key, value, triggerChange) { if (!key) return; // triggerChange设置true则把所有需要更新的数据添加到upldateProps之中 if (triggerChange && this.updateProps.indexOf(key) === -1) { this.updateProps.push(key); } this.data[key] = value; }; BizModel.prototype.delete = function (key) { if (!key) return; delete this.data[key]; }; BizModel.prototype.clear = function (key) { if (!key) return; this.data[key] = null; }; return BizModel; }(EventModel)); var PlainModel = /** @class */ (function (_super) { __extends(PlainModel, _super); function PlainModel(obj) { var _this = _super.call(this, obj) || this; _this.modelType = 'PlainModel'; return _this; } return PlainModel; }(BizModel)); var BizEntity = /** @class */ (function (_super) { __extends(BizEntity, _super); function BizEntity(obj, options) { var _this = _super.call(this) || this; _this.code = ''; _this.modelType = 'bizentity'; _this.uuid = uuid.v4(); _this.code = options.code; return _this; // var props: string[] = [] // if (obj) { // props = Object.keys(obj) // } // this.updateProps = [] // this.data = props.reduce((pre, next) => { // var item = new PlainModel({ // name: next, // value: obj[next] // TODO: 后续补充字段 // }) // pre[next] = item // // TODO: add和update要指定事件名 // item.addListener(() => { // this.updateLisener(this.getArrayData()) // }) // return pre // }, {} as any) // if (!options.code) { // throw Error('Entity code should not be null!') // } } BizEntity.prototype.get = function (key) { if (!key) return; return this.data[key]; }; BizEntity.prototype.getData = function () { var _data = this.data; var obj = {}; Object.keys(this.data).forEach(function (key) { obj[_data[key].get('name')] = _data[key].getValue(); }); return obj; }; BizEntity.prototype.setData = function (data) { var _data = this.data; Object.keys(data).forEach(function (key) { var field = _data[key]; if (field) { if (field.modelType == 'PlainModel') { field.setValue(data[key]); } } else { console.warn("field:" + key + ",value:" + data[key] + ", not defined in entity."); } //obj[_data[key].get('name')] = _data[key].getValue() }); }; BizEntity.prototype.getArrayData = function () { var _this = this; return Object.keys(this.data).map(function (key) { return { name: _this.data[key].get('name'), value: _this.data[key].getValue() }; }); }; BizEntity.prototype.getInstance = function () { return this; }; BizEntity.prototype.set = function (key, value, triggerChange) { if (!key) return; // triggerChange设置true则把所有需要更新的数据添加到upldateProps之中 if (triggerChange && this.updateProps.indexOf(key) === -1) { this.updateProps.push(key); } this.data[key] = value; }; BizEntity.prototype.delete = function (key) { if (!key) return; delete this.data[key]; }; BizEntity.prototype.clear = function (key) { if (!key) return; this.data[key] = null; }; return BizEntity; }(EventModel)); var urlcontext = function () { return (window.serviceproxy || "") + "/hypass/ws/rest" }; function save (entity) { var data = entity.getData(); var entityCode = entity.code; var url = "/service/save/" + entityCode; return new Promise(function (resolve, reject) { axios .post(urlcontext() + url, data) .then(function (data) { resolve(data); }) .catch(function (error) { reject(error); }); }); } function get (entity, params) { var entityCode = entity.code; if (!params.id) { throw Error('params should contain id as primary key, got params.id:' + params.id); } var url = "/service/get/" + entityCode + "/" + params.id; return new Promise(function (resolve, reject) { axios .get(urlcontext() + url) .then(function (data) { var res = data.data; if (res.status == 1) { entity.setData(res.data); resolve(res.data); } }) .catch(function (error) { reject(error); }); }); } var actions = { save: save, get: get }; var PlainEntity = /** @class */ (function (_super) { __extends(PlainEntity, _super); function PlainEntity(prop, options) { return _super.call(this, prop, options) || this; } PlainEntity.prototype.dispatch = function (method, params) { return actions[method](this, params); }; return PlainEntity; }(BizEntity)); function headerUtil () { var token = window.localStorage.getItem('token'); if (!token) { console.error('No token Exist!'); } else { return { headers: { token: token } } } } var listactions = { submit: function (data) { var _this = this; if (data && !(data instanceof Array)) { data = [data]; } return new Promise(function (resolve, reject) { axios .post(urlcontext() + '/' + _this.code + '/submit', { ids: data }, headerUtil()) .then(function (res) { _this.emit('afterSubmit', res.data.data); resolve(res.data.data); }) .catch(function (err) { reject(err); }); }); }, // search: function (data) { var _this = this; var params = this.getSearchParam(); return new Promise(function (resolve, reject) { axios .post(urlcontext() + '/' + _this.code + '/search', params, headerUtil()) .then(function (res) { _this.setData(res.data.data); _this.emit('afterSearch', res.data.data); resolve(res.data.data); }) .catch(function (err) { reject(err); }); }); }, delete: function (data) { var _this = this; var id = data; return new Promise(function (resolve, reject) { axios .delete(urlcontext() + '/' + _this.code + '/' + id) .then(function (res) { if (res.data.status == 1) { _this.emit('afterDelete'); resolve(res.data.data); } }) .catch(function (err) { reject('error'); }); }); }, }; var MetaModel = /** @class */ (function (_super) { __extends(MetaModel, _super); function MetaModel(obj) { var _this = _super.call(this, obj) || this; _this.modelType = 'MetaModel'; return _this; } MetaModel.prototype.clear = function () { var defaultValue = this.get('defaultValue'); this.setValue(defaultValue); this.emit('afterValueChange', { value: defaultValue }); }; MetaModel.prototype.getValue = function () { return this.data['value']; }; MetaModel.prototype.setValueOnly = function (newValue) { this.set('value', newValue); }; MetaModel.prototype.setValue = function (newValue, check) { var oldValue = this.getValue(); if (newValue === oldValue) return; var data = { value: newValue, oldValue: oldValue }; check = check !== false; check && this.emit('beforeValueChange', data); this.setValueOnly(newValue); check && this.emit('afterValueChange', data); check && this.updateLisener(this.getData()); }; MetaModel.prototype.setVisible = function () { }; MetaModel.prototype.setRequired = function () { }; MetaModel.prototype.setReadOnly = function () { }; MetaModel.prototype.setEditable = function () { }; MetaModel.prototype.addref = function () { }; MetaModel.prototype.removeref = function () { }; return MetaModel; }(BizModel)); var ColumnModel = /** @class */ (function (_super) { __extends(ColumnModel, _super); function ColumnModel(obj) { var _this = _super.call(this, obj) || this; _this.modelType = 'ColumnModel'; return _this; } return ColumnModel; }(MetaModel)); var RowModel = /** @class */ (function (_super) { __extends(RowModel, _super); function RowModel(obj) { var _this = _super.call(this, obj || {}) || this; _this.modelType = 'RowModel'; _this.rowData = {}; _this.selected = false; return _this; } RowModel.prototype.setData = function (rowData, rowInfo) { this.rowData = Object.assign({}, rowData); this.rowInfo = rowInfo; }; RowModel.prototype.getData = function () { return this.rowData; }; RowModel.prototype.setRowSelect = function (selected) { this.selected = selected; this.emit('rowSelectedChange', this.selected); }; RowModel.prototype.toggleRowSelect = function () { this.selected = !this.selected; this.emit('rowSelectedChange', this.selected); }; return RowModel; }(PlainModel)); var GridModel = /** @class */ (function (_super) { __extends(GridModel, _super); function GridModel(obj) { var _this = _super.call(this, obj) || this; _this.modelType = 'GridModel'; _this.columns = []; _this.selectedIndex = undefined; _this.rows = []; // 获取传入的columns,转化为gridmodel的列 if (!obj.columns) { throw Error('GridModel constructor: columns should be contain!'); } _this.columns = Object.keys(obj.columns).map(function (key) { // 非uimeta使用方式 var columnOpt = obj.columns[key]; if (typeof columnOpt === 'string') { return new ColumnModel({ key: key, label: '', initValue: columnOpt // TODO: 还有其他元数据的属性要补充 }); } else { return new ColumnModel(Object.assign(columnOpt, { key: key })); } }); return _this; } GridModel.prototype.getData = function () { return this.rows.map(function (row) { return row.getData(); }); }; GridModel.prototype.clearData = function () { this.rows = []; this.emit('clearData'); }; GridModel.prototype.setData = function (datas) { var _this = this; this.clearData(); datas.map(function (d, key) { _this.addRow(d, true); }); this.emit('afterSetData', this.getData()); }; GridModel.prototype.addRow = function (row, ignoreemit) { var newRow = this.createRow(row); this.rows.push(newRow); !ignoreemit && this.emit('afterAddRow', newRow); }; GridModel.prototype.removeRow = function (index, ignoreemit) { this.rows.splice(index, 1); !ignoreemit && this.emit('removeRow', this.rows); }; GridModel.prototype.removeRowById = function (rowId, ignoreemit) { var matchedRow = this.rows.map(function (row, index) { return { flag: row.rowInfo.rowId === rowId, index: index }; }).filter(function (item) { return item.flag; }); if (matchedRow && matchedRow.length > 0) { this.rows.splice(matchedRow[0].index, 1); } }; GridModel.prototype.getRow = function (index) { return this.rows[index]; }; GridModel.prototype.getRowByRowId = function (rowId) { var matchedRow = this.rows.filter(function (row) { return row.rowInfo.rowId === rowId; }); if (matchedRow && matchedRow.length > 0) { return matchedRow[0]; } else { return null; } }; GridModel.prototype.createRow = function (row) { // 字段以初始化的时候定义为准 var rowModel = new RowModel(); rowModel.setData(row, { rowId: uuid.v4() }); return rowModel; }; return GridModel; }(BizModel)); // { // fields: ["id", "firstName", "lastName", "addresses", "phone", "fullName", "company", "dateOfBirth", "email"], // sortBy: null, // data: { // _domain: null, // _domainContext: { // _id: null, // _model: "com.hypaas.contact.db.Contact" // }, // operator: "and", // criteria: [] // }, // limit: 40, // offset: 0 // } var PlainModel$1 = /** @class */ (function (_super) { __extends(PlainModel, _super); function PlainModel(obj, code) { var _this = _super.call(this, obj) || this; _this.modelType = 'SearchModel'; _this.set('fields', Object.keys(obj)); _this.set('criteria', []); _this.set('limit', 10); _this.set('offset', 0); _this.set('code', code); return _this; } PlainModel.prototype.getSearchParam = function () { return { fields: this.get('fields'), limit: this.get('limit'), offset: this.get('offset'), data: { _domain: null, _domainContext: { _id: null, _model: this.get('code'), }, operator: 'and', criteria: this.get('criteria'), }, }; }; return PlainModel; }(BizModel)); var ListEntity = /** @class */ (function (_super) { __extends(ListEntity, _super); function ListEntity(prop, options) { var _this = _super.call(this, prop, options) || this; _this.gridmodel = null; _this.searchmodel = null; // 处理models 分为gridmodel和searchmodel if (prop.models && prop.models.gridmodel) { var models = prop.models; _this.gridmodel = new GridModel({ columns: models.gridmodel, }); if (prop.models.searchmodel) { _this.searchmodel = new PlainModel$1(models.searchmodel, options.code); } else { _this.searchmodel = new PlainModel$1(models.gridmodel, options.code); } } else { throw Error('new ListEntity should contain models option'); } return _this; } ListEntity.prototype.dispatch = function (method, params) { if (!listactions[method]) { throw Error('dispatch ' + method + ' not found'); } var returnResult = this.emit('before' + method.replace(method[0], method[0].toUpperCase()), params); if (returnResult) { return listactions[method].call(this, params); } }; ListEntity.prototype.setData = function (datas) { var returnResult = this.emit('beforeSetData', datas); if (returnResult) { this.gridmodel.setData(datas); this.emit('afterSetData', this.gridmodel.getData()); } }; ListEntity.prototype.getData = function () { return this.gridmodel.getData(); }; ListEntity.prototype.getSearchParam = function () { return this.searchmodel.getSearchParam(); }; return ListEntity; }(BizEntity)); var cardactions = { detail: function (id) { var _this = this; var params = this.fetchParams; debugger; return new Promise(function (resolve, reject) { axios .post(urlcontext() + '/' + _this.code + '/' + id + '/fetch', params, headerUtil()) .then(function (res) { _this.setData(res.data.data); _this.emit('afterDetail', res.data.data); resolve(res.data.data); }) .catch(function (err) { reject('error'); }); }); }, save: function () { var _this = this; // 后续返回一个promise console.log('dispatch save action'); var data = this.getData(); return new Promise(function (resolve, reject) { axios .post(urlcontext() + '/' + _this.code, { data: data }, headerUtil()) .then(function (res) { _this.setData(res.data.data); _this.emit('afterSave', res.data.data); resolve(res.data.data); }) .catch(function (err) { reject('error'); }); }); }, submit: function (data) { // 后续返回一个promise var data = {}; data[this.primaryKey] = this.get(this.primaryKey).getValue(); console.log('dispatch subimt action, data:' + JSON.stringify(data)); return new Promise(function (resolve, reject) { resolve('ok'); this.emit('afterSubmit', data); }.bind(this)); }, }; var CardEntity = /** @class */ (function (_super) { __extends(CardEntity, _super); function CardEntity(prop, options) { var _this = _super.call(this, prop, options) || this; _this.childrenKeys = []; _this.mainKeys = []; _this.primaryKey = options.primaryKey || 'id'; // 处理models 分为gridmodel和searchmodel if (prop.models && prop.models.main) { var main = prop.models.main; var mainKeys = Object.keys(main); _this.fetchParams = { fields: mainKeys, related: {}, }; mainKeys.forEach(function (key) { _this.mainKeys.push(key); if (typeof main[key] === 'string') { _this.set(key, new MetaModel({ key: key, label: '', value: '', bRequired: false, })); } else { _this.set(key, new MetaModel(main[key])); } }); Object.keys(prop.models) .filter(function (key) { return key !== 'main'; }) .forEach(function (key) { _this.childrenKeys.push(key); _this.set(key, new GridModel({ columns: prop.models[key], })); _this.fetchParams.related[key] = Object.keys(prop.models[key]); }); } else { throw Error('new CardEntity should contain models option'); } return _this; } CardEntity.prototype.dispatch = function (method, params) { if (!cardactions[method]) { throw Error('dispatch ' + method + ' not found'); } var returnResult = this.emit('before' + method.replace(method[0], method[0].toUpperCase()), params); if (returnResult) { return cardactions[method].call(this, params); } }; CardEntity.prototype.empty = function () { var _this = this; // 主表字段设置成null this.mainKeys.forEach(function (key) { var metaModel = _this.get(key); metaModel && metaModel.setValue(null); }); // 子表设置成空数组 this.childrenKeys.forEach(function (key) { _this.get(key).setData([]); }); }; CardEntity.prototype.setData = function (datas) { var _this = this; Object.keys(datas).forEach(function (key) { // 如果是字表数据 if (_this.childrenKeys.indexOf(key) >= 0) { _this.get(key).setData(datas[key]); } else { var metaModel = _this.get(key); metaModel && metaModel.setValue(datas[key]); } }); this.emit('afterSetData', this.getData()); }; CardEntity.prototype.getData = function () { var _this = this; var main = {}; this.mainKeys.forEach(function (key) { main[key] = _this.get(key).getValue(); }); this.childrenKeys.forEach(function (key) { main[key] = _this.get(key).getData(); }); return main; }; return CardEntity; }(BizEntity)); var index = { PlainModel, PlainEntity, GridModel, ListEntity, MetaModel, CardEntity }; module.exports = index;