import React from 'react'; import moment from 'moment'; import constants from './constants/variable'; import Mock from 'mockjs' const Roles = { 0 : 'admin', 10: 'owner', 20: 'dev', 30: 'guest', 40: 'member' } const roleAction = { 'manageUserlist' : 'admin', 'changeMemberRole': 'owner', 'editInterface': 'dev', 'viewPrivateInterface': 'guest', 'viewGroup': 'guest' } exports.checkAuth = (action, role)=>{ return Roles[roleAction[action]] <= Roles[role]; } exports.formatTime = (timestamp) => { return moment.unix(timestamp).format("YYYY-MM-DD HH:mm:ss") } // 获取 YAPI LOGO 的 SVG // 参数 length 为 svg 的直径。 exports.logoSVG = (length) => ( Icon Created with Sketch. ); // 防抖函数,减少高频触发的函数执行的频率 // 请在 constructor 里使用: // import { debounce } from '$/common'; // this.func = debounce(this.func, 400); exports.debounce = (func, wait) => { let timeout; return function () { clearTimeout(timeout); timeout = setTimeout(func, wait); }; }; exports.simpleJsonPathParse = function (key, json){ if(!key || typeof key !== 'string' || key.indexOf('$.') !== 0 || key.length <= 2){ return null; } let keys = key.substr(2).split("."); keys = keys.filter(item=>{ return item; }) for(let i=0, l = keys.length; i< l; i++){ try{ let m = keys[i].match(/(.*?)\[([0-9]+)\]/) if(m){ json = json[m[1]][m[2]]; }else{ json = json[keys[i]]; } }catch(e){ json = null; break; } } return json; } exports.handleMockWord =(word) =>{ if(!word || typeof word !== 'string' || word[0] !== '@') return word; return Mock.mock(word); } // 从 Javascript 对象中选取随机属性 exports.pickRandomProperty = (obj) => { let result; let count = 0; for (let prop in obj) if (Math.random() < 1 / ++count) result = prop; return result; } exports.getImgPath = (path, type) => { let rate = window.devicePixelRatio >= 2 ? 2 : 1; return `${path}@${rate}x.${type}`; } function trim(str) { if (!str) { return str; } str = str + ''; return str.replace(/(^\s*)|(\s*$)/g, ''); } exports.trim = trim; exports.handlePath = (path) => { path = trim(path); if (!path) return path; if (path === '/') return ''; path = path[0] !== '/' ? '/' + path : path; path = path[path.length - 1] === '/' ? path.substr(0, path.length - 1) : path; return path; } // 名称限制 constants.NAME_LIMIT 字符 exports.nameLengthLimit = (type) => { // 返回字符串长度,汉字计数为2 const strLength = (str) => { let length = 0; for (let i = 0; i < str.length; i++) { str.charCodeAt(i) > 255 ? length += 2 : length++; } return length; } // 返回 form中的 rules 校验规则 return [{ required: true, validator(rule, value, callback) { const len = value ? strLength(value) : 0; if (len > constants.NAME_LIMIT) { callback('请输入' + type + '名称,长度不超过' + constants.NAME_LIMIT + '字符(中文算作2字符)!'); } else if (len === 0) { callback('请输入' + type + '名称,长度不超过' + constants.NAME_LIMIT + '字符(中文算作2字符)!'); } else { return callback(); } } }] }