dictionary.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { ObjectId } = require('mongoose').Types;
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. class DictionaryService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'dictionary');
  10. this.model = this.ctx.model.Dictionary;
  11. }
  12. // async update({ id, ...data }) {
  13. // await this.model.update({ _id: ObjectId(id) }, data);
  14. // return await this.model.find({ _id: ObjectId(id) });
  15. // }
  16. async xzqh({ pid }) {
  17. const query = {};
  18. const first = await this.model.findOne({ categroy: 'xzqh' });
  19. if (!first) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到行政区划(地区)字典内容,请确认字典表中是否有代码为"xzqh"的主目录字典');
  20. const { _id } = first;
  21. if (pid) query.pid = pid;
  22. else query.pid = _id;
  23. const res = await this.model.find(query);
  24. return res;
  25. }
  26. async delete({ id }) {
  27. let children = await this.dbFindChildren(id);
  28. children = children.map(i => ObjectId(i._id));
  29. children.push(ObjectId(id));
  30. const res = await this.model.deleteMany({ _id: children });
  31. return res;
  32. }
  33. async dbFindChildren(pid) {
  34. let toReturn = [];
  35. const res = await this.model.find({ pid }, '_id');
  36. toReturn = [ ...toReturn, ...res ];
  37. if (res.length > 0) {
  38. for (const i of res) {
  39. const { _id } = i;
  40. const list = await this.dbFindChildren(_id);
  41. toReturn = [ ...toReturn, ...list ];
  42. }
  43. }
  44. return toReturn;
  45. }
  46. async getTree(condition) {
  47. const dicList = await this.model.find(condition);
  48. let list = [];
  49. if (dicList && dicList.length > 0) {
  50. list = await this.toFindChildren(dicList);
  51. }
  52. const { categroy } = condition;
  53. if (categroy) {
  54. list = _.head(list);
  55. list = _.get(list, 'children', []);
  56. }
  57. return list;
  58. }
  59. toFindChildren(list) {
  60. list = JSON.parse(JSON.stringify(list));
  61. const head = list.filter(f => !f.pid);
  62. if (head.length <= 0) {
  63. throw new BusinessError(
  64. ErrorCode.DATA_INVALID,
  65. '需要将根目录加入整合函数的参数中'
  66. );
  67. }
  68. return this.findChildren(head, list);
  69. }
  70. findChildren(list, data) {
  71. for (const i of list) {
  72. let children = data.filter(f => f.pid === i._id);
  73. if (children.length > 0) children = this.findChildren(children, data);
  74. i.children = children;
  75. }
  76. return list;
  77. }
  78. }
  79. module.exports = DictionaryService;