1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- 'use strict';
- const assert = require('assert');
- const _ = require('lodash');
- const { ObjectId } = require('mongoose').Types;
- const { CrudService } = require('naf-framework-mongoose/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- class DictionaryService extends CrudService {
- constructor(ctx) {
- super(ctx, 'dictionary');
- this.model = this.ctx.model.Dictionary;
- }
- // async update({ id, ...data }) {
- // await this.model.update({ _id: ObjectId(id) }, data);
- // return await this.model.find({ _id: ObjectId(id) });
- // }
- async xzqh({ pid }) {
- const query = {};
- const first = await this.model.findOne({ categroy: 'xzqh' });
- if (!first) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到行政区划(地区)字典内容,请确认字典表中是否有代码为"xzqh"的主目录字典');
- const { _id } = first;
- if (pid) query.pid = pid;
- else query.pid = _id;
- const res = await this.model.find(query);
- return res;
- }
- 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 getTree(condition) {
- const dicList = await this.model.find(condition);
- let list = [];
- if (dicList && dicList.length > 0) {
- list = await this.toFindChildren(dicList);
- }
- const { categroy } = condition;
- if (categroy) {
- list = _.head(list);
- list = _.get(list, 'children', []);
- }
- 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 = DictionaryService;
|