helper.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. 'use strict';
  2. /**
  3. * 辅助方法扩展
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/9/28
  7. * @version
  8. */
  9. const zeroRange = 0.0000000001;
  10. module.exports = {
  11. /**
  12. * 生成随机字符串
  13. *
  14. * @param {Number} length - 需要生成字符串的长度
  15. * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
  16. * @return {String} - 返回生成结果
  17. */
  18. generateRandomString(length, type = 1) {
  19. length = parseInt(length);
  20. length = isNaN(length) ? 1 : length;
  21. let randSeed = [];
  22. let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  23. let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
  24. 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  25. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  26. switch (type) {
  27. case 1:
  28. randSeed = stringSeed.concat(numberSeed);
  29. stringSeed = numberSeed = null;
  30. break;
  31. case 2:
  32. randSeed = numberSeed;
  33. break;
  34. case 3:
  35. randSeed = stringSeed;
  36. break;
  37. default:
  38. break;
  39. }
  40. const seedLength = randSeed.length - 1;
  41. let result = '';
  42. for (let i = 0; i < length; i++) {
  43. const index = Math.ceil(Math.random() * seedLength);
  44. result += randSeed[index];
  45. }
  46. return result;
  47. },
  48. /**
  49. * 显示排序符号
  50. *
  51. * @param {String} field - 字段名称
  52. * @return {String} - 返回字段排序的符号
  53. */
  54. showSortFlag(field) {
  55. const sort = this.ctx.sort;
  56. if (!(sort instanceof Array) || sort.length !== 2) {
  57. return '';
  58. }
  59. sort[1] = sort[1].toUpperCase();
  60. return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
  61. },
  62. /**
  63. * 判断是否为ajax请求
  64. *
  65. * @param {Object} request - 请求数据
  66. * @return {boolean} 判断结果
  67. */
  68. isAjax(request) {
  69. let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
  70. headerInfo = headerInfo.toLowerCase();
  71. return headerInfo === 'xmlhttprequest';
  72. },
  73. /**
  74. * 模拟发送请求
  75. *
  76. * @param {String} url - 请求地址
  77. * @param {Object} data - 请求数据
  78. * @param {String} type - 请求类型(POST) POST | GET
  79. * @param {String} dataType - 数据类型 json|text
  80. * @return {Object} - 请求结果
  81. */
  82. async sendRequest(url, data, type = 'POST', dataType = 'json') {
  83. // 发起请求
  84. const response = await this.ctx.curl(url, {
  85. method: type,
  86. data,
  87. dataType,
  88. });
  89. if (response.status !== 200) {
  90. throw '请求失败';
  91. }
  92. return response.data;
  93. },
  94. /**
  95. * 深度验证数据
  96. *
  97. * @param {Object} rule - 数据规则
  98. * @return {void}
  99. */
  100. validate(rule) {
  101. // 先用内置的验证器验证数据
  102. this.ctx.validate(rule);
  103. // 然后再验证是否有多余的数据
  104. const postData = this.ctx.request.body;
  105. delete postData._csrf;
  106. const postDataKey = Object.keys(postData);
  107. const ruleKey = Object.keys(rule);
  108. // 自动增加字段则填充上,以防判断出错
  109. if (postData.create_time !== undefined) {
  110. ruleKey.push('create_time');
  111. }
  112. for (const tmp of postDataKey) {
  113. // 规则里面没有定义则抛出异常
  114. if (ruleKey.indexOf(tmp) < 0) {
  115. throw '参数不正确';
  116. }
  117. }
  118. },
  119. /**
  120. * 拆分path
  121. *
  122. * @param {String|Array} paths - 拆分字符
  123. * @param {String} symbol - 拆分符号
  124. * @return {Array} - 拆分结果
  125. */
  126. explodePath(paths, symbol = '.') {
  127. const result = [];
  128. paths = paths instanceof Array ? paths : [paths];
  129. for (const path of paths) {
  130. // 拆分数据
  131. const pathArray = path.split(symbol);
  132. // 用户缓存循环的数据
  133. const tmpArray = [];
  134. for (const tmp of pathArray) {
  135. // 每次循环都追加一个数据进去
  136. tmpArray.push(tmp);
  137. const tmpPathString = tmpArray.join(symbol);
  138. // 判断是否已经存在有对应数据
  139. if (result.indexOf(tmpPathString) >= 0) {
  140. continue;
  141. }
  142. result.push(tmpPathString);
  143. }
  144. }
  145. return result;
  146. },
  147. /**
  148. * 基于obj, 拷贝sObj中的内容
  149. * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
  150. * @param obj
  151. * @param sObj
  152. * @returns {any}
  153. */
  154. updateObj(obj, sObj) {
  155. if (!obj) {
  156. return JSON.parse(JSON.stringify(sObj));
  157. }
  158. const result = JSON.parse(JSON.stringify(obj));
  159. if (sObj) {
  160. for (const prop in sObj) {
  161. result[prop] = sObj[prop];
  162. }
  163. }
  164. return result;
  165. },
  166. /**
  167. * 在数组中查找
  168. * @param {Array} arr
  169. * @param name -
  170. * @param value
  171. * @returns {*}
  172. */
  173. findData(arr, name, value) {
  174. if (!arr instanceof Array) {
  175. throw '该方法仅用于数组查找';
  176. }
  177. if (arr.length === 0) { return undefined; }
  178. for (const data of arr) {
  179. if (data[name] == value) {
  180. return data;
  181. }
  182. }
  183. return undefined;
  184. },
  185. /**
  186. * 检查数字是否为0
  187. * @param {Number} value
  188. * @return {boolean}
  189. */
  190. checkZero(value) {
  191. return value && Math.abs(value) > zeroRange;
  192. },
  193. /**
  194. * 检查数字是否相等
  195. * @param {Number} value1
  196. * @param {Number} value2
  197. * @returns {boolean}
  198. */
  199. checkNumberEqual(value1, value2) {
  200. if (value1 && value2) {
  201. return Math.abs(value2 - value1) > zeroRange;
  202. } else {
  203. return (!value1 && !value2)
  204. }
  205. },
  206. /**
  207. * 比较编码
  208. * @param str1
  209. * @param str2
  210. * @param symbol
  211. * @returns {number}
  212. */
  213. compareCode(str1, str2, symbol = '-') {
  214. if (!str1) {
  215. return -1;
  216. } else if (!str2) {
  217. return 1;
  218. }
  219. const path1 = str1.split(symbol);
  220. const path2 = str2.split(symbol);
  221. for (let i = 0, iLen = Math.min(path1.length, path2.length); i < iLen; i++) {
  222. if (path1 < path2) {
  223. return -1;
  224. } else if (path1 > path2) {
  225. return 1;
  226. }
  227. }
  228. return path1.length - path2.length;
  229. },
  230. /**
  231. * 树结构节点排序,要求最顶层节点须在同一父节点下
  232. * @param treeNodes
  233. * @param idField
  234. * @param pidField
  235. */
  236. sortTreeNodes (treeNodes, idField, pidField) {
  237. const result = [];
  238. const getFirstLevel = function (nodes) {
  239. let result;
  240. for (const node of nodes) {
  241. if (!result || result > node.level) {
  242. result = node.level;
  243. }
  244. }
  245. return result;
  246. }
  247. const getLevelNodes = function (nodes, level) {
  248. const children = nodes.filter(function (a) {
  249. return a.level = level;
  250. });
  251. children.sort(function (a, b) {
  252. return a.order - b.order;
  253. })
  254. return children;
  255. }
  256. const getChildren = function (nodes, node) {
  257. const children = nodes.filter(function (a) {
  258. return a[pidField] = node[idField];
  259. });
  260. children.sort(function (a, b) {
  261. return a.order - b.order;
  262. })
  263. return children;
  264. }
  265. const addSortNodes = function (nodes) {
  266. for (let i = 0; i< nodes.length; i++) {
  267. result.push(nodes[i]);
  268. addSortNodes(getChildren(nodes[i]));
  269. }
  270. }
  271. const firstLevel = getFirstLevel(treeNodes);
  272. addSortNodes(getLevelNodes(treeNodes, firstLevel));
  273. },
  274. /**
  275. * 判断当前用户是否有指定权限
  276. *
  277. * @param {Number|Array} permission - 权限id
  278. * @return {Boolean} - 返回判断结果
  279. */
  280. hasPermission(permission) {
  281. let result = false;
  282. try {
  283. const sessionUser = this.ctx.session.sessionUser;
  284. if (sessionUser.permission === undefined) {
  285. throw '不存在权限数据';
  286. }
  287. let currentPermission = sessionUser.permission;
  288. if (currentPermission === '') {
  289. throw '权限数据为空';
  290. }
  291. // 管理员则直接返回结果
  292. if (currentPermission === 'all') {
  293. return true;
  294. }
  295. currentPermission = currentPermission.split(',');
  296. permission = permission instanceof Array ? permission : [permission];
  297. let counter = 0;
  298. for (const tmp of permission) {
  299. if (currentPermission[tmp] !== undefined) {
  300. counter++;
  301. }
  302. }
  303. result = counter === permission.length;
  304. } catch (error) {
  305. result = false;
  306. }
  307. return result;
  308. },
  309. };