UNPKG

gxd-vue-library

Version:

依赖与element Ui插件库,聚福宝福利PC端插件库

651 lines (589 loc) 16.9 kB
'use strict'; const beautifier = require('js-beautify'); const mock = require('./mock'); const path = require('path'); const logDir = require('./../path').logDir; const buildDir = require('./../path').buildDir; const rootDir = require('./../path').rootDir; const fileHelper = require('./../fileHepler'); let {getTestData} = mock; let { getMapUrl, getMapMethod } = require('./handleRules'); const { resultKey, defaultFormType, newMapRule } = require('./../config/config'); const clog = require('./../clog'); const randomChar = (len) => { let arrstring = 'qwertyuiopasdfghjklzxcvbnm123456789QWERTYUIOPASDFGHJKLZXCVBNM'.split(''); let str = ''; for (let i = 0; i < len; i++) { let Range = arrstring.length - 1; let Rand = Math.random(); let index = Math.round(Rand * Range); str += arrstring[index]; } return str; } /** * @description 检查变量类型 * @param obj * @returns {*} */ const checkVarType = (obj) => { let toString = Object.prototype.toString; let map = { '[object Boolean]': 'boolean', '[object Number]': 'number', '[object String]': 'string', '[object Function]': 'function', '[object Array]': 'array', '[object Date]': 'date', '[object RegExp]': 'regExp', '[object Undefined]': 'undefined', '[object Null]': 'null', '[object Object]': 'object' }; return map[toString.call(obj)]; }; /** * @description 检查对象或者数组是否为空 * @param obj * @return boolean */ const isEmpty = (obj) => { if (checkVarType(obj) === 'array' || checkVarType(obj) === 'object' ) { let str = JSON.stringify(obj); return str === '{}' || str === '[]'; } else { console.log('isEmpty.error', obj); throw new Error('只支持数组与JSON对象格式'); } }; /** * @description 检测查找数组是否在原数组中 * @param sourceArray 原数组 * @param findArray 查找数组 * @returns {boolean} */ const inArray = (sourceArray = [], findArray = []) => { if (this.checkVarType(sourceArray) === 'array' && this.checkVarType(findArray) === 'array') { let sourceArraylen = sourceArray.length; let find = JSON.parse(JSON.stringify(findArray)); let temp = []; for (let i = 0; i < sourceArraylen; i++) { let sourceVal = sourceArray[i]; for (let k = 0; k < find.length; k++) { if (find[k] === sourceVal) { temp.push(true); find.splice(k, 1); break; } } } return findArray.length === temp.length; } else { return false; } }; /** * @description 特殊字符串转化成数组 * @param str {String|Array} 转化字符串 * @param type 返回数据类型 1=>数组 2=>小驼峰格式(axxxxBxxxCxxx) 3=>AXXXX_BXXX_CXXX, 4,AxxxxBxxxCxxx * 例如: AxxxxBxxxCxxx => ['axxxx','bxxx', 'cxxx']; * 例如: axxxxBxxxCxxx => ['axxxx','bxxx', 'cxxx']; */ const strToArray = (str, type=1) => { //console.log('strToArray',str); let temp = []; //数组 if(checkVarType(str) === 'array') temp = str; //字符串 else{ let reg = /[A-Z]/; let word = ''; str.split('').map((char, index) => { if (index === 0) { word = char.toLocaleLowerCase(); } else { if (reg.test(char)) { temp.push(word); word = char.toLocaleLowerCase(); } else { word += char; if (index === (str.length - 1)) temp.push(word); } } }); } if (type === 1) return temp; if (type === 3){ return temp.map(item => { return item.toLocaleUpperCase(); }).join('_'); } if (type === 2){ return temp.map((item,index) => { if(index === 0) return item.toLocaleLowerCase(); else return `${item.substr(0,1).toLocaleUpperCase()}${item.substr(1).toLocaleLowerCase()}` }).join(''); } if(type === 4){ return temp.map((item, index) => { return `${item.substr(0, 1).toLocaleUpperCase()}${item.substr(1).toLocaleLowerCase()}` }).join(''); } }; /** * @description 替换路径中的// * @param dir */ const replaceDir = (dir) => { return path.normalize(dir) }; /** * @description 获取build.json文件 * @param key 支持a.b访问方式 1、all=>返回全部信息 2、a.b返回局部信息 * @return {String|Number|Array|Boolean|null} */ const getBuildInfo =(key)=>{ let buildPath = replaceDir(rootDir + '/build.json'); let build = fileHelper.readFileSync(buildPath); let temp = {}; let info = {}; try{ let data = info = JSON.parse(build); }catch (e) { console.error(e); temp = null; } if(key === 'all') return info; return temp; }; /** * @description 获取一个时间版本号 * @returns {`${number}${number}${number}${number}${number}${number}`} */ const getVersion = () => { let time = new Date(); let year = time.getFullYear(); let month = time.getMonth() + 1; let day = time.getDate(); let hour = time.getHours(); let minutes = time.getMinutes(); let s = time.getSeconds(); return `${year}${month}${day}${hour}${minutes}${s}`; } /*** * @description 列表数据默认数据项 * @type {*[]} */ const table = [ {prop: 'id', align: 'center', width: '50px', label: 'ID'}, {prop: 'name', align: 'center', width: '200px', label: '名称'}, {prop: 'package_name', align: 'center', minWidth: '200px', label: '套餐名称'}, {prop: 'created', align: 'center', width: '150px', label: '创建时间'}, {prop: 'updated', align: 'center', width: '150px', label: '修改时间'}, {prop: 'status', align: 'center', width: '140px', label: '状态', type: 'status'}, {prop: 'image', align: 'center', width: '140px', label: 'ICON', type: 'image'}, { prop: '@operate', value: [ {ui: 'link', icon: 'el-icon-view', target: '_blank', name: '查看', type: 'primary'}, {ui: 'button', icon: 'el-icon-delete', name: '删除', type: 'primary'}, ] }, ]; const getLogs = (type , model)=>{ if (!fileHelper.existFileSync(logDir)) { fileHelper.mkdirSync(buildDir, 'log'); } return JSON.stringify({ created: dateToTime(Math.floor(new Date().getTime() / 1000)), type: type, model: model }, null, 2) } /** * @description 列表数据生成默认数配置 * @type {*[]} */ const tableRule = { id: 1000 + '@increment', name: '@cname(3,3)', package_name: '@ctitle(5,15)', created: "@datetime('yyyy-MM-dd HH:mm:ss')", updated: "@now('yyyy-MM-dd HH:mm:ss')", 'status|+1': ['Y', 'X'], image: "@image('120x90')" }; const deep = (obj)=>{ return JSON.parse(JSON.stringify(obj)); }; /** * @description JS,CSS,HTML文件代码美化 * https://blog.csdn.net/u012732909/article/details/121791340 * @param content 美化字符串 * @param type [js_beautify,css_beautify,html_beautify] 默认:js_beautify * @param options jsbeautifier配置信息 */ const beautifyFile = (content, type = 'js_beautify', options = {}) => { content = content.replace(/(\r\n|\n)\s*/g, '\n') .replace(/\(\n/g, '(') .replace(/,\n/g, ',') .replace(/\/\*\*/g, '\n/**') .replace(/\n\/\//g, '\n\n//'); if(type === 'html_beautify') { options = { wrap_attributes: 'force-expand-multiline', wrap_attributes_indent_size: 2, ...options } } if(type=== 'js_beautify') { options = { ...options, "brace_style": "preserve-inline", } } return beautifier[type](content, Object.assign({ indent_with_tabs: false, indent_size: 2, jslint_happy: true, end_with_newline: true, space_after_anon_function: true, }, options)) }; /** * @description 时间戳转年月日 * @param time {String|Number} 时间戳 (秒) * @param type */ const dateToTime = (time, type='all')=> { let date = new Date(Number(time) * 1000); let y = date.getFullYear(); let m = date.getMonth() + 1; m = m < 10 ? ('0' + m) : m; let d = date.getDate(); d = d < 10 ? ('0' + d) : d; let h = date.getHours(); h = h < 10 ? ('0' + h) : h; let minute = date.getMinutes(); let second = date.getSeconds(); minute = minute < 10 ? ('0' + minute) : minute; second = second < 10 ? ('0' + second) : second; if(type === 'all') return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second; if(type === 'date') return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + '00'; if(type=== 'str') return `${y}${m}${d}${h}${minute}${second}`; } /** * @description 获取内部使用KEY值 * @param item 模块对象 * @param urls urls对象 * @param type 返回数据类型 true 返回大小名称 (模块+ 路径) * @returns {*} */ const getInKey = (item, urls, type = true)=>{ let reg = /(:[a-zA-z0-9_]+)/g; /** * 判断url格式是否带有:xx占位符带有自定义方法:例如: * /user/:xx/:xxx/app * /user/:xx/:xxx */ if(reg.test(urls.path)) { if(urls.mapFn) { return type ? strToArray(urls.mapFn, 3): strToArray(urls.mapFn, 2); } clog(`配置错误文件路径:${item.filePath}`, 'red'); clog('接口信息为"/user/:xx/:xxx/app"格式,请配置自定义方法,mapFn:xxxx', 'red'); clog(`模型名字:${item.name}`, 'red'); clog('当前接口配置信息为:', 'red'); clog(JSON.stringify(urls, null, 2), 'red'); process.exit(0); } let key = null, fn = null; /** * @description 兼容老模式 */ if(!newMapRule) { let lastArr = urls.path.split('/'); let last = lastArr[lastArr.length - 1]; last = last.replace(/([_\-\.])/g, '@').split('@'); if (urls.prefix) last = [urls.prefix].concat(last); last = last.map(val => { return `${val.slice(0, 1).toLocaleUpperCase() + val.slice(1)}`; }); let fnString = last.join('_'); let keyString = last.join(''); key = `${item.name.toLocaleUpperCase()}_${fnString.toLocaleUpperCase()}`; fn = `${item.name.toLocaleLowerCase()}${keyString}`; return type ? key : fn; } /** * @description 新模式 */ let nameArr = []; //自定义方法 if(urls.mapFn) { nameArr = strToArray(urls.mapFn, 1); } //根据 前缀? + 模块 + path(最后一位) + 后缀? else{ let lastArr = urls.path.split('/'); let last = lastArr[lastArr.length - 1]; if (urls.prefix) nameArr = nameArr.concat(strToArray(urls.prefix, 1)); nameArr = nameArr.concat(strToArray(item.name, 1)); nameArr = nameArr.concat(last.replace(/([_\-\.])/g, '@').split('@')); if (urls.suffix) nameArr = nameArr.concat(strToArray(urls.suffix, 1)); } return type ? strToArray(nameArr, 3) : strToArray(nameArr, 2); }; /** * @description 获取模块内API * @param item * @returns {*} */ const getUrls = (item)=>{ let tempUrl = { title: item.title, name: item.name, vuex: item.vuex, fileName: `${item.name}.js`, allMapFn: [], filePath: item.filePath, filePathName: item['filePathName'], value: [], }; item.model.map(it => { if (it.disabled) { //非严格模式 if(!it.isRule) { tempUrl.value.push({ title: it.title, rootTitle: item.title, url: it.path, key: getInKey(item, it), fnName: getInKey(item, it, false), name: item.name, }) } //严格模式 else { let temp = []; Object.keys(it.roles).map(method=>{ let tempUrl = getMapUrl(method, it); let tempData = getMapMethod(method, item, it); temp.push({ url: tempUrl, rootTitle: item.title, name: item.name, ...tempData, }) }); tempUrl.value = tempUrl.value.concat(temp); } } }); return tempUrl.value.length > 0 ? tempUrl : null; }; /** * @description 生成API配置 * @param item */ const getApiData = (item)=>{ let ApiTemp = { title: item.title, name: item.name, vuex: item.vuex, fileName: `${item.name}.js`, filePathName: item['filePathName'], value: [], }; item.model.map(it => { //非严格模式 if(it.isRule === false) { let method = 'get'; let isParams = true; let defaultParamsSave = null; //存储参数对象 let defaultParams = null; //当有配置data参数,请求方法设置为post if (it.data) { method = 'post'; defaultParamsSave = it.data; } //当有配置params参数,请求方法设置为post if(it.params) { method = 'get'; defaultParamsSave = it.params; delete it.data; } //非严格模式删除query字段 delete it.query; //已经设置方法使用方法 if(it.method) { method = it.method; } //无配置参数 if (!it.params && !it.data) { isParams = false; } //设置默认值 if(defaultParamsSave !== null) { defaultParams = {}; Object.keys(defaultParamsSave).map(key=>{ if(defaultParamsSave[key].length === 4) { defaultParams[key]= defaultParamsSave[key][3]; } }); if(isEmpty(defaultParams)) defaultParams = null } ApiTemp.value.push({ ...it, key: getInKey(item, it), fnName: getInKey(item, it, false), hasSpecialPlaceholder: /(:[a-zA-z0-9_]+)/g.test(it.path), isParams, method, formType: it['formType'] || defaultFormType, sort: (item.sort || 10), resultKey: it['resultKey'] || resultKey, isConsole: it['isConsole'] || false, defaultParams: defaultParams ? JSON.stringify(defaultParams) : defaultParams, }); } //严格模式 else{ let temp = []; Object.keys(it['roles']).map(method=>{ let tempData = getMapMethod(method, item, it); temp.push({ ...tempData, sort: (item.sort || 10), }) }); ApiTemp.value = ApiTemp.value.concat(temp); } }); return ApiTemp.value.length > 0 ? ApiTemp : null; }; /** * @description 生成Pages配置 * @param item */ const getPagesData = (item)=> { let Api = getApiData(item); let types = Api.value.map(it=>{ return it['key']; }); let fnNames = Api.value.map(it => { return it['fnName']; }); let states = []; Api.value.map(it => { if(it['state']) states.push(it['state']); }); let pages = []; let pagesBaseTemp = { modeTitle: item.title, modelName: item.name, vuex: item.vuex, sort: (item.sort || 10), fileName: `${item.name}.js`, time: dateToTime(Math.floor(new Date().getTime() / 1000)), types, fnNames, states }; if(item.pages) { item.pages.map(it=>{ let pageName = ['pages',item.name]; if(this.prefix) pageName.push(this.prefix); pageName.push(it.name); if (!it.table) it.table = deep(table); if (!it.tableRule) it.tableRule = deep(tableRule); pageName = pageName.map(val => { return `${val.slice(0, 1).toLocaleUpperCase() + val.slice(1)}`; }).join(''); let count = 10; if(it.type === 'info') count = 1; let testData = getTestData(count, it.tableRule); pages.push({...deep(pagesBaseTemp), ...it, sort: (item.sort || 10), pageName, testData: JSON.stringify(testData)}); }) } return pages; }; /** * @description 获取npm参数 */ const getArgv = ()=> { let arr = JSON.parse(JSON.stringify(process.argv)); arr.splice(0,2); arr = arr.map(item=>{ return item.replace(/[\[\]]/g, '') }); return arr; }; /** * @description 显示分割线 * @param clog * @param pos {String} start=>换行在前面 end=> 换行在后面 默认:end */ const logsLine = (clog, pos= 'end') => { if(pos === 'end') clog('---------------------------------------------------------\n', 'white'); else clog('\n---------------------------------------------------------', 'white'); }; /** * @description 获取打包参数 * @returns {{layout: boolean, watch: boolean, UNI_PLATFORM: *, domain: *, NODE_ENV: *, type: string | string, isOpenDir: boolean}} */ const getParams = () => { const { NODE_ENV, UNI_PLATFORM, watch, type, cover, domain, service, permissionsCover, permissionsTagsViewCover } = process.env; return { NODE_ENV, UNI_PLATFORM, isOpenDir: true, watch: watch === 'true', type: type || 'test', cover: cover === 'true', domain, service, permissionsCover: permissionsCover ===undefined?true:(permissionsCover === 'true'), permissionsTagsViewCover: permissionsTagsViewCover === undefined ? true : (permissionsTagsViewCover === 'true') }; }; module.exports = { deep, beautifyFile, getInKey, getUrls, getApiData, isEmpty, checkVarType, inArray, dateToTime, getArgv, getPagesData, getLogs, getVersion, logsLine, getBuildInfo, replaceDir, strToArray, randomChar, getParams };