'use strict'; const assert = require('assert'); const _ = require('lodash'); const moment = require('moment'); const { ObjectId } = require('mongoose').Types; const { CrudService } = require('naf-framework-mongoose/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; class MenuService extends CrudService { constructor(ctx) { super(ctx, 'menu'); this.model = this.ctx.model.Menu; } async delete({ id }) { let children = await this.dbFindChildren(id); children = children.map(i => ObjectId(i._id)); children.push(ObjectId(id)); const res = await this.model.deleteMany({ _id: children }); return res; } async dbFindChildren(pid) { let toReturn = []; const res = await this.model.find({ pid }, '_id'); toReturn = [ ...toReturn, ...res ]; if (res.length > 0) { for (const i of res) { const { _id } = i; const list = await this.dbFindChildren(_id); toReturn = [ ...toReturn, ...list ]; } } return toReturn; } async findProject(condition) { const { project } = condition; assert(project, '缺少需要查询的项目名称'); const res = await this.model.find({ _tenant: project }).sort({ sort: -1 }); let list = []; if (res && res.length > 0) { list = await this.toFindChildren(res); } return list; } toFindChildren(list) { list = JSON.parse(JSON.stringify(list)); const head = list.filter(f => !f.pid); if (head.length <= 0) throw new BusinessError(ErrorCode.DATA_INVALID, '需要将根目录加入整合函数的参数中'); return this.findChildren(head, list); } findChildren(list, data) { for (const i of list) { let children = data.filter(f => f.pid === i._id); if (children.length > 0) children = this.findChildren(children, data); i.children = children; } return list; } } module.exports = MenuService;