'use strict'; const assert = require('assert'); const Service = require('egg').Service; class MenuService extends Service { constructor(ctx) { super(ctx); this.model = this.ctx.model.Menu; this.column = this.ctx.model.Column; this.pages = this.ctx.model.Pages; } async create({ name, code, date, type, url, column, pages, parentCode, isshow, template }) { assert(name, '名称不存在'); assert(code, '编码不存在'); assert(type, '类型不存在'); try { const res = await this.model.findOne({ code }); if (res) return { errcode: -1001, errmsg: '编码已存在', data: '' }; const item = await this.model.create({ name, code, date, type, url, column, pages, parentCode, isshow, template }); return { errcode: 0, errmsg: '', data: item }; } catch (error) { throw error; } } async update({ id, name, date, type, url, column, pages, parentCode, isshow, template }) { assert(id, 'id不存在'); try { const res = await this.model.findOne({ _id: id }); if (!res) return { errcode: -1001, errmsg: '数据不存在', data: '' }; await this.model.updateOne({ _id: id }, { name, date, type, url, column, pages, parentCode, isshow, template }); return { errcode: 0, errmsg: '', data: 'update' }; } catch (error) { throw error; } } async delete({ id }) { assert(id, 'id不存在'); try { const res = await this.model.findOne({ _id: id }); if (!res) return { errcode: -1001, errmsg: '数据不存在', data: '' }; const column = await this.column.findOne({ bind: res.code }); const pages = await this.pages.findOne({ bind: res.code }); if (column || pages) return { errcode: -1001, errmsg: '存在绑定关系,不能删除', data: '' }; await this.model.remove({ _id: id }); return { errcode: 0, errmsg: '', data: 'delete' }; } catch (error) { throw error; } } async query({ skip, limit, name, code, parentCode, isshow }) { const filter = {}; if (name || code || parentCode) filter.$or = []; if (name) filter.$or.push({ name: { $regex: name } }); if (code) filter.$or.push({ code: { $regex: code } }); if (parentCode) filter.$or.push({ parentCode: { $regex: parentCode } }); if (isshow) filter.isshow = isshow; try { let res; const total = await this.model.find({ ...filter }); if (skip && limit) { res = await this.model.find({ ...filter }) .skip(Number(skip) * Number(limit)) .limit(Number(limit)) .sort({ date: 1 }); } else { res = await this.model.find({ ...filter }).sort({ date: 1 }); } return { errcode: 0, errmsg: '', data: res, total: total.length }; } catch (error) { throw error; } } async menuList({ code }) { const list = await this.model.find(); const lists = []; const children = ({ code }) => { const item = list.filter(j => code === j.parentCode).map(e => children(e)); lists.push(...item); return code; }; children({ code }); return lists; } } module.exports = MenuService;