context.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. 'use strict';
  2. const jwt = require('jsonwebtoken');
  3. // const { parse } = require('urlencode');
  4. module.exports = {
  5. resultOK(result, desc) {
  6. this.body = { errorNo: 0, result, errorDesc: desc };
  7. this.status = 200;
  8. },
  9. resultFail(desc) {
  10. this.body = { errorNo: 500, errorDesc: desc };
  11. this.status = 200;
  12. },
  13. adminFail(desc) {
  14. this.body = { code: 500, success: false, result: null, message: desc };
  15. this.status = 200;
  16. },
  17. adminOK(result, desc) {
  18. this.body = { code: 200, success: true, result, message: desc };
  19. this.status = 200;
  20. },
  21. bodyResult(code, result, desc) {
  22. this.body = { errorNo: code, result, errorDesc: desc };
  23. this.status = 200;
  24. },
  25. async jwtSign(payload, secret, options) {
  26. return jwt.sign(payload, secret, options);
  27. },
  28. async jwtVerify(token, secret, options) {
  29. function verify() {
  30. return new Promise((resolve, reject) => {
  31. jwt.verify(token, secret, options, function(err, decoded) {
  32. let result = {};
  33. if (err) {
  34. result.verify = false;
  35. result.message = err.message;
  36. } else {
  37. result.verify = true;
  38. result.message = decoded;
  39. }
  40. resolve(result);
  41. });
  42. });
  43. }
  44. let ret = await verify();
  45. return ret;
  46. },
  47. SqlFmtTime(field, target) {
  48. return `date_format(${field},'%Y-%m-%d') as ${target?target:field}`;
  49. },
  50. async pageSelect(query, table, field, filter, it) {
  51. let mysql = this.app.mysql;
  52. let pageNo = query.pageNo;
  53. let pageSize = query.pageSize;
  54. if (pageNo == undefined) pageNo = 1;
  55. if (pageSize == undefined) pageSize = 10;
  56. pageNo = parseInt(pageNo);
  57. pageSize = parseInt(pageSize);
  58. let ret = { records: [], total: 0, };
  59. let where = filter;
  60. let sql = `select ${field} from ${table} ${where}`
  61. console.log(sql);
  62. let total = await mysql.query(`select count(*) as count from ${table} ` + where);
  63. ret.total = total[0].count;
  64. let data = await mysql.query(`${sql} limit ${(pageNo-1)*pageSize},${pageSize}`);
  65. if (it) {
  66. data.forEach(element => {
  67. it(element);
  68. });
  69. }
  70. ret.records = data;
  71. return ret;
  72. },
  73. async queryHandleByService(service, fnName) {
  74. let ctx = this;
  75. let data = ctx.request.query;
  76. let ret = await service[fnName](data);
  77. ctx.adminOK(ret);
  78. },
  79. async queryHandleByServiceInApp(service, fnName) {
  80. let ctx = this;
  81. let data = ctx.request.query;
  82. let ret = await service[fnName](data);
  83. ctx.resultOK(ret);
  84. },
  85. async bodyHandleByService(service, fnName, desc) {
  86. let ctx = this;
  87. let data = ctx.request.body;
  88. let ret = await service[fnName](data);
  89. ctx.adminOK(ret, desc);
  90. },
  91. async bodyHandleByServiceInApp(service, fnName, desc) {
  92. let ctx = this;
  93. let data = ctx.request.body;
  94. let ret = await service[fnName](data);
  95. ctx.resultOK(ret, desc);
  96. },
  97. nameFmt2Camel(v) {
  98. function parse(obj) {
  99. if (typeof obj != 'object') return;
  100. let keys = Object.keys(obj);
  101. keys.forEach(k => {
  102. let ks = k.split("_");
  103. if (ks.length > 1) {
  104. let n = ks.length;
  105. for (let i = 1; i < n; i++) {
  106. let kname = ks[i];
  107. ks[i] = kname[0].toUpperCase() + kname.slice(1);
  108. }
  109. let camelKey = ks.join("");
  110. obj[camelKey] = obj[k];
  111. delete obj[k];
  112. }
  113. });
  114. }
  115. let isArr = Array.isArray(v);
  116. if (isArr) {
  117. v.forEach(c => parse(c));
  118. return;
  119. }
  120. parse(v);
  121. },
  122. nameFmtCamel2UnderLine(v) {
  123. function parse(obj) {
  124. if (typeof obj != 'object') return;
  125. let keys = Object.keys(obj);
  126. keys.forEach(k => {
  127. let ks = k.split("_");
  128. if (ks.length == 1) { //下划线模式的不用转
  129. let n = k.length;
  130. let words = [];
  131. let lastStart = 0;
  132. for (let i = 0; i < n; i++) {
  133. let char = k[i];
  134. if (char >= 'A' && char <= 'Z') {
  135. if (i > 0) {
  136. let s = k.substr(lastStart, i - lastStart);
  137. words.push(s.toLocaleLowerCase());
  138. lastStart = i;
  139. }
  140. }
  141. if (i == n - 1 && lastStart > 0) {
  142. let s = k.substr(lastStart, i - lastStart + 1);
  143. words.push(s.toLocaleLowerCase());
  144. }
  145. }
  146. if (words.length > 1) {
  147. let nkey = words.join("_");
  148. obj[nkey] = obj[k];
  149. delete obj[k];
  150. }
  151. }
  152. });
  153. }
  154. let isArr = Array.isArray(v);
  155. if (isArr) {
  156. v.forEach(c => parse(c));
  157. return;
  158. }
  159. parse(v);
  160. },
  161. //要求数据结构id, parent_id=0
  162. fmt2Tree(ret, fn) {
  163. let nodes = {};
  164. ret.forEach(r => {
  165. nodes[r.id] = r;
  166. });
  167. let treeList = [];
  168. let cacheNodes = {};
  169. function parseNode(node) {
  170. let extObj = fn(node);
  171. if (!extObj) return;
  172. let parentId = node.parent_id;
  173. if (parentId == undefined) parentId = node.parentId;
  174. if (parentId == 0) { //根节点
  175. let cnode = cacheNodes[node.id];
  176. if (treeList.indexOf(cnode) < 0) { //还没有加入List
  177. let curNode = { children: [], ...extObj };
  178. treeList.push(curNode);
  179. cacheNodes[node.id] = curNode;
  180. return curNode;
  181. }
  182. return cnode;
  183. } else {
  184. //处理父亲节点
  185. let parentId = node.parent_id;
  186. if (parentId == undefined) parentId = node.parentId;
  187. let parentNode = nodes[parentId];
  188. let parent = cacheNodes[parentNode.id];
  189. if (!parent) {
  190. parent = parseNode(parentNode);
  191. if (!parent) return;
  192. }
  193. //处理自己
  194. let curNode = { children: [], ...extObj };
  195. parent.children.push(curNode);
  196. cacheNodes[node.id] = curNode;
  197. return curNode;
  198. }
  199. }
  200. ret.forEach(node => {
  201. parseNode(node);
  202. });
  203. function checkNode(node) {
  204. node.isLeaf = node.children.length < 1;
  205. if (node.children.length < 1) {
  206. node.children = null;
  207. node.isLeaf = true;
  208. return;
  209. }
  210. node.children.forEach(c => checkNode(c));
  211. }
  212. treeList.forEach(c => checkNode(c));
  213. return treeList;
  214. },
  215. getStaticUrl(uri) {
  216. let config = this.app.config;
  217. return config.server.publicHost + uri;
  218. },
  219. async getLoginedUser() {
  220. let ctx = this;
  221. let authToken = ctx.header.authorization;
  222. if (!authToken) {
  223. return null;
  224. }
  225. let config = this.app.config.loginAdmin;
  226. let ret = await ctx.jwtVerify(authToken, config.secret);
  227. if (!ret.verify) {
  228. null;
  229. }
  230. return ret.message;
  231. }
  232. };