123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- 'use strict';
- const { CrudService } = require('naf-framework-mongoose-free/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const _ = require('lodash');
- const assert = require('assert');
- const { ObjectId } = require('mongoose').Types;
- //
- class DirService extends CrudService {
- constructor(ctx) {
- super(ctx, 'dir');
- this.model = this.ctx.model.Dir;
- this.tableModel = this.ctx.model.Table;
- }
- async delete(filter) {
- assert(filter);
- const { _id, id } = filter;
- const target = _id || id;
- // 递归删除: 删除内部文件夹和表 的数据
- await this.deleteOthers(target);
- await this.model.findByIdAndDelete(target).exec();
- return 'ok';
- }
- async deleteOthers(target) {
- const dirIds = await this.deleteDirAndTableIds(target);
- await this.model.deleteMany({ _id: dirIds });
- }
- /**
- * 获取指定文件夹下的文件夹id和表id集合
- * @param {String} target 文件夹id
- */
- async deleteDirAndTableIds(target) {
- const result = [];
- const dirs = await this.model.find({ super: target }, { _id: 1 }).lean();
- // 表没有下级,直接删除
- await this.tableModel.deleteMany({ dir: target });
- if (dirs.length > 0) {
- const dirIds = dirs.map((i) => ObjectId(i._id).toString());
- result.push(...dirIds);
- for (const dir of dirs) {
- const r = await this.deleteDirAndTableIds(dir._id);
- result.push(...r);
- }
- }
- return result;
- }
- }
- module.exports = DirService;
|