menu.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const moment = require('moment');
  5. const { ObjectId } = require('mongoose').Types;
  6. const { CrudService } = require('naf-framework-mongoose/lib/service');
  7. const { BusinessError, ErrorCode } = require('naf-core').Error;
  8. class MenuService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'menu');
  11. this.model = this.ctx.model.Menu;
  12. }
  13. async delete({ id }) {
  14. let children = await this.dbFindChildren(id);
  15. children = children.map(i => ObjectId(i._id));
  16. children.push(ObjectId(id));
  17. const res = await this.model.deleteMany({ _id: children });
  18. return res;
  19. }
  20. async dbFindChildren(pid) {
  21. let toReturn = [];
  22. const res = await this.model.find({ pid }, '_id');
  23. toReturn = [ ...toReturn, ...res ];
  24. if (res.length > 0) {
  25. for (const i of res) {
  26. const { _id } = i;
  27. const list = await this.dbFindChildren(_id);
  28. toReturn = [ ...toReturn, ...list ];
  29. }
  30. }
  31. return toReturn;
  32. }
  33. async findProject(condition) {
  34. const { project } = condition;
  35. assert(project, '缺少需要查询的项目名称');
  36. const res = await this.model.find({ _tenant: project }).sort({ sort: -1 });
  37. let list = [];
  38. if (res && res.length > 0) {
  39. list = await this.toFindChildren(res);
  40. }
  41. return list;
  42. }
  43. toFindChildren(list) {
  44. list = JSON.parse(JSON.stringify(list));
  45. const head = list.filter(f => !f.pid);
  46. if (head.length <= 0) throw new BusinessError(ErrorCode.DATA_INVALID, '需要将根目录加入整合函数的参数中');
  47. return this.findChildren(head, list);
  48. }
  49. findChildren(list, data) {
  50. for (const i of list) {
  51. let children = data.filter(f => f.pid === i._id);
  52. if (children.length > 0) children = this.findChildren(children, data);
  53. i.children = children;
  54. }
  55. return list;
  56. }
  57. }
  58. module.exports = MenuService;