UNPKG

foreasydata

Version:

EasyData for Web Utils.

659 lines (656 loc) 18.3 kB
const { Tree } = require('fordata') /** * 是否为空数据 * @param {*} value 数据值 * @returns */ const isNull = (value) => { return (value === undefined) || (value === null) || (value === "") } /** * localStorage字典解码 * @param {String} key localStorage的key * @returns JSON String */ const getStorage = (key) => { let destr = `&#${(localStorage[key] || '').split('x0x').map((item, index) => { return ((+`0x${item}`) - 2 ** (index % 10)) }).join(';&#')};` return destr.replace(/&#(\d+);/g, function(match, decode) { return String.fromCharCode(decode); }) } module.exports = class EasyData { /** * * @param {String} moduleCode 模板编码 * @returns */ constructor(moduleCode, headers) { this.moduleCode = moduleCode this.headers = { 'Authorization': localStorage.easy_token, 'Content-Type': 'application/json;charset=UTF-8', ...headers } this.currentCategory = null return this } /** * 请求 * @param {Object} options 请求配置 * @returns */ async fetch(options = {}) { let { url = '/', method = 'get', data = {}, headers } = options if (method == 'get') { if (url.includes('?')) { url += `&${new URLSearchParams(data).toString()}` } else { url += `?${new URLSearchParams(data).toString()}` } data = null } try { let resp = await fetch(`${window.EASY_ROOT || ''}${url}`, { method, body: data, headers: new Headers(headers || this.headers) }) let res = null try { res = await resp.json() } catch { res = { success: false, msg: resp } } return new Promise((resolve) => { if (res.success) { resolve({ isSuccess: res.success, data: res.data, msg: res.msg }) } else { resolve({ isSuccess: false, data: [], msg: res.msg || res.error }) } }) } catch (err) { return new Promise((resolve) => { resolve({ isSuccess: false, data: [], msg: err }) }) } } /** * 初始化获取模板详情 * @returns Promise */ init() { return new Promise(async (resolve) => { let res = await this.fetch({ url: '/api/easydata/md/api/getModule', // url: '/api/easydata/md/api/getModule', data: { code: this.moduleCode } }) this.isSuccess = res.isSuccess this.msg = res.msg if (res.isSuccess) { this.module = res.data.map(item => { return { ...item, value: '' } }) } resolve(this) }) } /** * 处理模板字段 * @returns Object */ getColumns() { let show = [] let select = [] let input = [] this.module.forEach(item => { if (item.unionKeyType === 'DICT') { if (localStorage['D']) { item.dics = (JSON.parse(getStorage('D'))[item.unionTableId] || []).map(item => { return { text: item.label, value: item.value } }) } if (localStorage[item.unionTableColumn]) { item.dics = JSON.parse(localStorage[item.unionTableColumn]) } item.dics.unshift({ text: `全部${item.frontComment || item.columnComment}`, value: '' }) } if (item.unionKeyType === 'RELATION') { if (localStorage['RELATION']) { item.dics = (JSON.parse(getStorage('RELATION'))[item.unionTableId] || []).map(item => { return { text: item.label, value: item.value } }) } if (localStorage[item.unionTableColumn]) { item.dics = JSON.parse(localStorage[item.unionTableColumn]) } item.dics.unshift({ text: `全部${item.frontComment || item.columnComment}`, value: '' }) } if (item.unionKeyType === 'CATEGORY') { new Tree({ id: 'id' }) // this.getCategoryByParentId(item.unionTableColumn, JSON.parse(localStorage.DIC_TREE)[item.unionTableId]) item.category = item.unionTableColumn ? (JSON.parse(localStorage.DIC_TREE)[item.unionTableId]).findChildren(item.unionTableColumn).toTree(item.unionTableColumn) : JSON.parse(localStorage.DIC_TREE)[item.unionTableId] item.categoryText = '' } if (item.isShow) { show.push(item) } if (item.opType) { if (/(select)|(category)/ig.test(item.componentType)) { select.push(item) } if (/(input)/ig.test(item.componentType)) { input.push(item) } } }) return { show, search: { select, input } } } /** * 获取列表参数 * @returns Object */ getListParams() { let conditions = {} this.module && this.module.forEach(item => { if (item.opType) { let { tableName, columnName, value, opType, defaultText, parseValue } = item if (!conditions[tableName]) { conditions[tableName] = { data: !isNull(value || defaultText || value) ? [ { columnName, value: parseValue || value || defaultText || value, opType } ] : [], tableName } } else { if (!isNull(value || defaultText || value)) { conditions[tableName].data.push({ columnName, value: parseValue || value || defaultText || value, opType }) } } } }) return { code: this.moduleCode, conditions: Object.values(conditions) } } /** * 字典编码转换为名称 * @param {Array} dics 字典项集合 * @param {String} code 字典编码 * @returns String */ parseDicCodeToName(dics, code) { return (dics.find(item => (item.value === code) || (item.text === code)) || { text: '' }).text } /** * 字典名称转换为编码 * @param {Array} dics 字典项集合 * @param {String} code 字典编码 * @returns String */ parseDicNameToCode(dics, name) { return (dics.find(item => (item.text === name) || (item.value === name)) || { value: '' }).value } /** * 列表数据字典转换 * @param {Array} list * @returns Array */ parseList(list) { list.forEach(item => { Object.keys(item).forEach(k => { let column = this.module.find(i => i.frontName == k) if (column && column.length) { item[k] = (item[k] || '').substring(0, column.length) } if (column && column.dics && item[k]) { if (column.unionKeyType === 'DICT') { item[k] = this.parseDicCodeToName(column.dics, item[k]) } } }) }) return list } /** * 获取添加参数 * @returns Object */ getAddParams() { let conditions = {} this.module.forEach(item => { let { tableName, columnName, value, dics, isPrimaryKey, componentType, defaultText, category } = item if (dics) { value = this.parseDicNameToCode(dics, value) } if (/(time)/ig.test(componentType) && (!value.includes('-'))) { value = new Date(+value).format('yyyy-MM-dd hh:mm:ss') } if ((!isPrimaryKey) && (value !== '-')) { if (!conditions[tableName]) { if (!isNull(value || defaultText || value)) { conditions[tableName] = { data: [ { columnName, value: value || defaultText || value } ], tableName } } } else { if (!isNull(value || defaultText || value)) { conditions[tableName].data.push({ columnName, value: value || defaultText || value }) } } } }) return { code: this.moduleCode, conditions: Object.values(conditions) } } /** * 获取更新参数 * @returns Array */ getUpdateParams() { let params = {} let condition = this.module.filter(item => item.isPrimaryKey).map(item => { return { ...item, opType: 'eq' } }) if (!condition.length) { return } this.module.forEach(item => { let { tableName, columnName, value, dics, frontName, opType, componentType, defaultText } = item if (/(time)/ig.test(componentType) && (!value.includes('-'))) { value = new Date(+value).format('yyyy-MM-dd hh:mm:ss') } if (dics) { value = this.parseDicNameToCode(dics, value) } if (!params[tableName]) { if (!isNull(value || defaultText || value)) { params[tableName] = { data: [ { columnName, value: value || defaultText || value, // opType: opType || 'eq' } ], condition, tableName } } } else { if (!isNull(value || defaultText || value)) { params[tableName].data.push({ columnName, value: value || defaultText || value, // opType: opType || 'eq' }) } } }) return { code: this.moduleCode, columns: Object.values(params) } return Object.values(params) } /** * 获取更新参数 V2 * @returns Array */ getUpdateParamsV2() { let params = { columns: [] } let condition = this.module.filter(item => item.isPrimaryKey).map(item => { return { ...item, opType: 'eq' } }) if (!condition.length) { return } this.module.forEach(item => { let { tableName, columnName, value, dics, frontName, opType, componentType, defaultText, isPrimaryKey } = item if (/(time)/ig.test(componentType) && (!value.includes('-'))) { value = new Date(+value).format('yyyy-MM-dd hh:mm:ss') } if (dics) { value = this.parseDicNameToCode(dics, value) } if (!isPrimaryKey) { params.columns.push({ columnName, value, tableName }) } // if (!params[tableName]) { // if (!isNull(value || defaultText || value)) { // params[tableName] = { // data: [ // { // columnName, // value: value || defaultText || value, // tableName // // opType: opType || 'eq' // } // ], // // condition, // tableName // } // } // } else { // if (!isNull(value || defaultText || value)) { // params[tableName].data.push({ // columnName, // value: value || defaultText || value, // tableName, // // opType: opType || 'eq' // }) // } // } }) return { code: this.moduleCode, conditions: condition, columns: params.columns } return Object.values(params) } /** * 获取删除参数 * @returns Object */ getDelParams() { let params = {} this.module.forEach(item => { let { tableName, columnName, value, frontName, isPrimaryKey } = item if (isPrimaryKey) { params = { code: this.moduleCode, condition: [ { columnName, value, opType: 'eq' } ], tableName } } }) if (!params.condition) { return } return params } /** * 获取详情参数 * @param {*} id 主键ID * @returns Object */ getDetailParams(id) { let conditions = {} this.module.forEach(item => { let { tableName, columnName, value, dics, frontName, isPrimaryKey, componentType } = item if (dics && value) { value = this.parseDicCodeToName(dics, value) } if (isPrimaryKey) { value = id } if (!conditions[tableName]) { if (!isNull(value)) { conditions[tableName] = { data: [ { columnName, value, opType: 'eq' } ], tableName } } } else { if (!isNull(value)) { conditions[tableName].data.push({ columnName, value }) } } }) return { code: this.moduleCode, conditions: Object.values(conditions) } } /** * 新增数据 * @returns Promise */ add(params = {}) { return this.fetch({ url: '/api/easydata/md/api/add', method: 'post', data: JSON.stringify({ ...this.getAddParams(), ...params }) }) } /** * 删除数据 * @returns Promise */ del() { return this.fetch({ url: '/api/easydata/md/api/delete', data: JSON.stringify(this.getDelParams()), method: 'post' }) } /** * 更新数据 * @returns Promise */ update(params = {}) { return this.fetch({ url: '/api/easydata/md/api/update', data: JSON.stringify({ ...this.getUpdateParams(), ...params }), method: 'post' }) } /** * 更新数据 V2 * @returns Promise */ updateV2(params = {}) { return this.fetch({ url: '/api/easydata/md/api/update', data: JSON.stringify({ ...this.getUpdateParamsV2(), ...params }), method: 'post' }) } /** * 获取列表数据 * @param {*} params 自定义扩展参数 * @returns Promise */ getList(params = {}) { return new Promise(async (resolve) => { let res = await this.fetch({ url: '/api/easydata/md/api/page', // url: '/api/easydata/md/api/page', data: JSON.stringify({ ...this.getListParams(), ...params }), method: 'post' }) let results = res results = this.parseList(res.data.list || []) resolve(results) }) } /** * 获取列表数据 * @param {*} params 自定义扩展参数 * @returns Promise */ getListTotal(params = {}) { return new Promise(async (resolve) => { let res = await this.fetch({ url: '/api/easydata/md/api/page', // url: '/api/easydata/md/api/page', data: JSON.stringify({ ...this.getListParams(), ...params }), method: 'post' }) let results = res results = this.parseList(res.data.list || []) resolve({ ...res.data, list: results, }) }) } /** * 获取详情 * @param {*} id 主键ID * @param {Boolean} isParseObject 是否转换成对象 * @returns Promise */ getDetail(id, isParseObject = false) { return new Promise(async (resolve) => { let res = await this.fetch( { url: '/api/easydata/md/api/get', data: JSON.stringify(this.getDetailParams(id)), method: 'post' } ) let columns = [] res.data.forEach(item => { columns = [...columns, ...item.columns] }) this.module.forEach(item => { columns.forEach(i => { if (item.columnName == i.columnName && item.tableName == i.tableName) { item.value = i.columnValue if (/(time|date)/ig.test(item.componentType) && (!`${item.value}`.includes('-'))) { if (item.value) { item.value = new Date(+(item.value)).format('yyyy-MM-dd hh:mm:ss') } } } }) }) this.getColumns() if (isParseObject) { let result = {} this.module.forEach(i => { result[i.frontName] = i.value }) resolve(result) } resolve(res) }) } /** * 根据主键获取表信息 * @returns Object */ getTableInfo() { return this.module.find(item => item.isPrimaryKey) } getCategoryByParentId(parentId, tree) { if (!this.currentCategory) { tree.forEach(item => { if (item.id === parentId) { this.currentCategory = item.children } else { if (item.children) { this.getCategoryByParentId(parentId, item.children) } } }) } } /** * 获取统计数据 * @function * @param {Array|Object} params - 请求参数 * @returns {Promise} */ getStats(params = {}) { return new Promise(async (resolve) => { let res = await this.fetch({ url: '/api/easydata/stats/model/data', method: 'post', data: JSON.stringify(Array.isArray(params) ? params : [params]) }) let tmp = JSON.parse(JSON.stringify(res)) tmp.data.forEach(stats => { if (stats.data.x) { let results = [] stats.data.x.forEach((item, index) => { let y = [] stats.data.y.forEach(i => { y.push(i[index]) }) results.push({ ...item, count: y.length > 1 ? y : y[0] }) }) stats.data = results } }) res.data.forEach(stats => { if (stats.data.y) { stats.data.y = stats.data.y.length > 1 ? stats.data.y : stats.data.y[0] } }) this.isSuccess = res.isSuccess this.msg = res.msg resolve({ isSuccess: this.isSuccess, msg: this.msg, data: tmp.data.length > 1 ? tmp.data : tmp.data[0], origion: res.data.length > 1 ? res.data : res.data[0] }) }) } }