helper.js 7.0 KB

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