template_controller.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. /**
  3. * 指标模板控制器
  4. *
  5. * @author Mai
  6. * @data 2018/4/19
  7. * @version
  8. */
  9. // excel解析
  10. const excel = require('node-xlsx');
  11. const sendToWormhole = require('stream-wormhole');
  12. module.exports = app => {
  13. class TemplateController extends app.BaseController {
  14. /**
  15. * 指标模板页面
  16. *
  17. * @param {object} ctx - egg全局context
  18. * @return {void}
  19. */
  20. async index (ctx) {
  21. const node = await ctx.service.templateNode.getAllDataByCondition({template_id: 1});
  22. const treeNode = ctx.helper.convertData(node, true, 'node_id', 'node_pid');
  23. const renderData = {
  24. nodes: JSON.stringify(treeNode),
  25. }
  26. await this.layout('template/index.ejs', renderData, 'template/modal.ejs');
  27. }
  28. async uploadExcel(ctx) {
  29. let stream;
  30. try {
  31. stream = await ctx.getFileStream();
  32. const fileName = this.app.baseDir + '/app/public/template/uploads/' + stream.filename;
  33. // 保存文件
  34. await ctx.helper.saveStreamFile(stream, fileName);
  35. // 读取文件
  36. const sheet = excel.parse(fileName);
  37. if (!sheet || sheet.length === 0 || sheet[0] === undefined || sheet[0].data === undefined) {
  38. throw 'excel没有对应数据';
  39. }
  40. const result = await ctx.service.templateNode.importData(sheet);
  41. if (!result) {
  42. throw '导入数据失败';
  43. }
  44. ctx.redirect('/template');
  45. } catch (err) {
  46. console.log(err);
  47. // 失败需要消耗掉stream 以防卡死
  48. if (stream) {
  49. await sendToWormhole(stream);
  50. }
  51. //this.setMessage(err.toString(), this.messageType.ERROR);
  52. ctx.redirect('/template');
  53. }
  54. }
  55. }
  56. return TemplateController;
  57. }