dir.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 query(query) {
  15. const dirs = await this.model.find(query).lean();
  16. const firstLevelDir = dirs.filter((f) => !f.super);
  17. const inDirDirs = dirs.filter((f) => f.super);
  18. const newDir = this.ctx.service.table.makeDir(firstLevelDir, inDirDirs);
  19. return newDir;
  20. }
  21. async delete(filter) {
  22. assert(filter);
  23. const { _id, id } = filter;
  24. const target = _id || id;
  25. // 递归删除: 删除内部文件夹和表 的数据
  26. await this.deleteOthers(target);
  27. await this.model.findByIdAndDelete(target).exec();
  28. return 'ok';
  29. }
  30. async deleteOthers(target) {
  31. const dirIds = await this.deleteDirAndTableIds(target);
  32. await this.model.deleteMany({ _id: dirIds });
  33. }
  34. /**
  35. * 获取指定文件夹下的文件夹id和表id集合
  36. * @param {String} target 文件夹id
  37. */
  38. async deleteDirAndTableIds(target) {
  39. const result = [];
  40. const dirs = await this.model.find({ super: target }, { _id: 1 }).lean();
  41. // 表没有下级,直接删除
  42. await this.tableModel.deleteMany({ dir: target });
  43. if (dirs.length > 0) {
  44. const dirIds = dirs.map((i) => ObjectId(i._id).toString());
  45. result.push(...dirIds);
  46. for (const dir of dirs) {
  47. const r = await this.deleteDirAndTableIds(dir._id);
  48. result.push(...r);
  49. }
  50. }
  51. return result;
  52. }
  53. }
  54. module.exports = DirService;