helper.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. 'use strict';
  2. /**
  3. * 辅助方法扩展
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/9/28
  7. * @version
  8. */
  9. const zeroRange = 0.0000000001;
  10. const fs = require('fs');
  11. const streamToArray = require('stream-to-array');
  12. const _ = require('lodash');
  13. module.exports = {
  14. /**
  15. * 生成随机字符串
  16. *
  17. * @param {Number} length - 需要生成字符串的长度
  18. * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
  19. * @return {String} - 返回生成结果
  20. */
  21. generateRandomString(length, type = 1) {
  22. length = parseInt(length);
  23. length = isNaN(length) ? 1 : length;
  24. let randSeed = [];
  25. let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  26. let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
  27. 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  28. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  29. switch (type) {
  30. case 1:
  31. randSeed = stringSeed.concat(numberSeed);
  32. stringSeed = numberSeed = null;
  33. break;
  34. case 2:
  35. randSeed = numberSeed;
  36. break;
  37. case 3:
  38. randSeed = stringSeed;
  39. break;
  40. default:
  41. break;
  42. }
  43. const seedLength = randSeed.length - 1;
  44. let result = '';
  45. for (let i = 0; i < length; i++) {
  46. const index = Math.ceil(Math.random() * seedLength);
  47. result += randSeed[index];
  48. }
  49. return result;
  50. },
  51. /**
  52. * 字节转换
  53. * @param bytes 字节
  54. * @return {string} 大小
  55. */
  56. bytesToSize(bytes) {
  57. if (bytes === 0) return '0 B';
  58. let k = 1024;
  59. const sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  60. let i = Math.floor(Math.log(bytes) / Math.log(k));
  61. //return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
  62. return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  63. },
  64. /**
  65. * 显示排序符号
  66. *
  67. * @param {String} field - 字段名称
  68. * @return {String} - 返回字段排序的符号
  69. */
  70. showSortFlag(field) {
  71. const sort = this.ctx.sort;
  72. if (!(sort instanceof Array) || sort.length !== 2) {
  73. return '';
  74. }
  75. sort[1] = sort[1].toUpperCase();
  76. return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
  77. },
  78. /**
  79. * 判断是否为ajax请求
  80. *
  81. * @param {Object} request - 请求数据
  82. * @return {boolean} 判断结果
  83. */
  84. isAjax(request) {
  85. let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
  86. headerInfo = headerInfo.toLowerCase();
  87. return headerInfo === 'xmlhttprequest';
  88. },
  89. /**
  90. * 模拟发送请求
  91. *
  92. * @param {String} url - 请求地址
  93. * @param {Object} data - 请求数据
  94. * @param {String} type - 请求类型(POST) POST | GET
  95. * @param {String} dataType - 数据类型 json|text
  96. * @return {Object} - 请求结果
  97. */
  98. async sendRequest(url, data, type = 'POST', dataType = 'json') {
  99. // 发起请求
  100. const response = await this.ctx.curl(url, {
  101. method: type,
  102. data,
  103. dataType,
  104. });
  105. if (response.status !== 200) {
  106. throw '请求失败';
  107. }
  108. return response.data;
  109. },
  110. /**
  111. * 深度验证数据
  112. *
  113. * @param {Object} rule - 数据规则
  114. * @return {void}
  115. */
  116. validate(rule) {
  117. // 先用内置的验证器验证数据
  118. this.ctx.validate(rule);
  119. // 然后再验证是否有多余的数据
  120. const postData = this.ctx.request.body;
  121. delete postData._csrf;
  122. const postDataKey = Object.keys(postData);
  123. const ruleKey = Object.keys(rule);
  124. // 自动增加字段则填充上,以防判断出错
  125. if (postData.create_time !== undefined) {
  126. ruleKey.push('create_time');
  127. }
  128. for (const tmp of postDataKey) {
  129. // 规则里面没有定义则抛出异常
  130. if (ruleKey.indexOf(tmp) < 0) {
  131. throw '参数不正确';
  132. }
  133. }
  134. },
  135. /**
  136. * 拆分path
  137. *
  138. * @param {String|Array} paths - 拆分字符
  139. * @param {String} symbol - 拆分符号
  140. * @return {Array} - 拆分结果
  141. */
  142. explodePath(paths, symbol = '.') {
  143. const result = [];
  144. paths = paths instanceof Array ? paths : [paths];
  145. for (const path of paths) {
  146. // 拆分数据
  147. const pathArray = path.split(symbol);
  148. // 用户缓存循环的数据
  149. const tmpArray = [];
  150. for (const tmp of pathArray) {
  151. // 每次循环都追加一个数据进去
  152. tmpArray.push(tmp);
  153. const tmpPathString = tmpArray.join(symbol);
  154. // 判断是否已经存在有对应数据
  155. if (result.indexOf(tmpPathString) >= 0) {
  156. continue;
  157. }
  158. result.push(tmpPathString);
  159. }
  160. }
  161. return result;
  162. },
  163. /**
  164. * 基于obj, 拷贝sObj中的内容
  165. * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
  166. * @param obj
  167. * @param sObj
  168. * @returns {any}
  169. */
  170. updateObj(obj, sObj) {
  171. if (!obj) {
  172. return JSON.parse(JSON.stringify(sObj));
  173. }
  174. const result = JSON.parse(JSON.stringify(obj));
  175. if (sObj) {
  176. for (const prop in sObj) {
  177. result[prop] = sObj[prop];
  178. }
  179. }
  180. return result;
  181. },
  182. /**
  183. * 在数组中查找
  184. * @param {Array} arr
  185. * @param name -
  186. * @param value
  187. * @returns {*}
  188. */
  189. findData(arr, name, value) {
  190. if (!arr instanceof Array) {
  191. throw '该方法仅用于数组查找';
  192. }
  193. if (arr.length === 0) { return undefined; }
  194. for (const data of arr) {
  195. if (data[name] == value) {
  196. return data;
  197. }
  198. }
  199. return undefined;
  200. },
  201. /**
  202. * 检查数字是否为0
  203. * @param {Number} value
  204. * @return {boolean}
  205. */
  206. checkZero(value) {
  207. return value && Math.abs(value) > zeroRange;
  208. },
  209. /**
  210. * 检查数字是否相等
  211. * @param {Number} value1
  212. * @param {Number} value2
  213. * @returns {boolean}
  214. */
  215. checkNumberEqual(value1, value2) {
  216. if (value1 && value2) {
  217. return Math.abs(value2 - value1) > zeroRange;
  218. } else {
  219. return (!value1 && !value2)
  220. }
  221. },
  222. /**
  223. * 比较编码
  224. * @param str1
  225. * @param str2
  226. * @param symbol
  227. * @returns {number}
  228. */
  229. compareCode(str1, str2, symbol = '-') {
  230. if (!str1) {
  231. return -1;
  232. } else if (!str2) {
  233. return 1;
  234. }
  235. const path1 = str1.split(symbol);
  236. const path2 = str2.split(symbol);
  237. for (let i = 0, iLen = Math.min(path1.length, path2.length); i < iLen; i++) {
  238. if (path1 < path2) {
  239. return -1;
  240. } else if (path1 > path2) {
  241. return 1;
  242. }
  243. }
  244. return path1.length - path2.length;
  245. },
  246. /**
  247. * 树结构节点排序,要求最顶层节点须在同一父节点下
  248. * @param treeNodes
  249. * @param idField
  250. * @param pidField
  251. */
  252. sortTreeNodes (treeNodes, idField, pidField) {
  253. const result = [];
  254. const getFirstLevel = function (nodes) {
  255. let result;
  256. for (const node of nodes) {
  257. if (!result || result > node.level) {
  258. result = node.level;
  259. }
  260. }
  261. return result;
  262. }
  263. const getLevelNodes = function (nodes, level) {
  264. const children = nodes.filter(function (a) {
  265. return a.level = level;
  266. });
  267. children.sort(function (a, b) {
  268. return a.order - b.order;
  269. })
  270. return children;
  271. }
  272. const getChildren = function (nodes, node) {
  273. const children = nodes.filter(function (a) {
  274. return a[pidField] = node[idField];
  275. });
  276. children.sort(function (a, b) {
  277. return a.order - b.order;
  278. })
  279. return children;
  280. }
  281. const addSortNodes = function (nodes) {
  282. for (let i = 0; i< nodes.length; i++) {
  283. result.push(nodes[i]);
  284. addSortNodes(getChildren(nodes[i]));
  285. }
  286. }
  287. const firstLevel = getFirstLevel(treeNodes);
  288. addSortNodes(getLevelNodes(treeNodes, firstLevel));
  289. },
  290. /**
  291. * 判断当前用户是否有指定权限
  292. *
  293. * @param {Number|Array} permission - 权限id
  294. * @return {Boolean} - 返回判断结果
  295. */
  296. hasPermission(permission) {
  297. let result = false;
  298. try {
  299. const sessionUser = this.ctx.session.sessionUser;
  300. if (sessionUser.permission === undefined) {
  301. throw '不存在权限数据';
  302. }
  303. let currentPermission = sessionUser.permission;
  304. if (currentPermission === '') {
  305. throw '权限数据为空';
  306. }
  307. // 管理员则直接返回结果
  308. if (currentPermission === 'all') {
  309. return true;
  310. }
  311. currentPermission = currentPermission.split(',');
  312. permission = permission instanceof Array ? permission : [permission];
  313. let counter = 0;
  314. for (const tmp of permission) {
  315. if (currentPermission[tmp] !== undefined) {
  316. counter++;
  317. }
  318. }
  319. result = counter === permission.length;
  320. } catch (error) {
  321. result = false;
  322. }
  323. return result;
  324. },
  325. /**
  326. * 将文件流的数据保存至本地文件
  327. * @param stream
  328. * @param fileName
  329. * @returns {Promise<void>}
  330. */
  331. async saveStreamFile(stream, fileName) {
  332. // 读取字节流
  333. const parts = await streamToArray(stream);
  334. // 转化为buffer
  335. const buffer = Buffer.concat(parts);
  336. // 写入文件
  337. await fs.writeFileSync(fileName, buffer);
  338. },
  339. /**
  340. * 检查code是否是指标模板数据
  341. * @param {String} code
  342. * @returns {boolean}
  343. */
  344. validBillsCode(code) {
  345. const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
  346. const reg2 = /([a-z0-9]+$)/i;
  347. return reg1.test(code) && reg2.test(code);
  348. },
  349. getNumberFormatter(decimal) {
  350. if (decimal <= 0) {
  351. return "0";
  352. }
  353. let pre = "0.";
  354. for (let i = 0; i < decimal; i++) {
  355. pre += "#"
  356. }
  357. return pre;
  358. },
  359. /**
  360. * 根据单位查找对应的清单精度
  361. * @param {tenderInfo.precision} list - 清单精度列表
  362. * @param {String} unit - 单位
  363. * @returns {number}
  364. */
  365. findPrecision(list, unit) {
  366. if (unit) {
  367. for (const p in list) {
  368. if (list[p].unit && list[p].unit === unit) {
  369. return list[p];
  370. }
  371. }
  372. }
  373. return list.other;
  374. },
  375. /**
  376. * 检查数据中的精度
  377. * @param {Object} Obj - 检查的数据
  378. * @param {Array} fields - 检查的属性
  379. * @param {Number} precision - 精度
  380. * @constructor
  381. */
  382. checkFieldPrecision(Obj, fields, precision) {
  383. if (Obj) {
  384. for (const field of fields) {
  385. if (Obj[field]) {
  386. Obj[field] = this.round(Obj[field], precision);
  387. }
  388. }
  389. }
  390. },
  391. /**
  392. * 四舍五入(统一,方便以后万一需要置换)
  393. * @param {Number} value - 舍入的数字
  394. * @param {Number} decimal - 要保留的小数位数
  395. * @returns {*}
  396. */
  397. round(value, decimal) {
  398. return _.round(value, decimal);
  399. },
  400. };