dir.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const { ObjectId } = require('mongoose').Types;
  7. //
  8. class DirService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'dir');
  11. this.model = this.ctx.model.Dir;
  12. this.tableModel = this.ctx.model.Table;
  13. }
  14. async delete(filter) {
  15. assert(filter);
  16. const { _id, id } = filter;
  17. const target = _id || id;
  18. // 递归删除: 删除内部文件夹和表 的数据
  19. await this.deleteOthers(target);
  20. await this.model.findByIdAndDelete(target).exec();
  21. return 'ok';
  22. }
  23. async deleteOthers(target) {
  24. const dirIds = await this.deleteDirAndTableIds(target);
  25. await this.model.deleteMany({ _id: dirIds });
  26. }
  27. /**
  28. * 获取指定文件夹下的文件夹id和表id集合
  29. * @param {String} target 文件夹id
  30. */
  31. async deleteDirAndTableIds(target) {
  32. const result = [];
  33. const dirs = await this.model.find({ super: target }, { _id: 1 }).lean();
  34. // 表没有下级,直接删除
  35. await this.tableModel.deleteMany({ dir: target });
  36. if (dirs.length > 0) {
  37. const dirIds = dirs.map((i) => ObjectId(i._id).toString());
  38. result.push(...dirIds);
  39. for (const dir of dirs) {
  40. const r = await this.deleteDirAndTableIds(dir._id);
  41. result.push(...r);
  42. }
  43. }
  44. return result;
  45. }
  46. }
  47. module.exports = DirService;