'use strict'; const assert = require('assert'); const Service = require('egg').Service; class ColumnService extends Service { constructor(ctx) { super(ctx); this.model = this.ctx.model.Column; this.content = this.ctx.model.Content; this.menu = this.ctx.model.Menu; this.imgnews = this.ctx.model.Imgnews; } async create({ name, code }) { assert(name, '名称不存在'); assert(code, '编码不存在'); try { const res = await this.model.findOne({ code }); if (res) return { errcode: -1001, errmsg: '编码已存在', data: '' }; const item = await this.model.create({ name, code }); return { errcode: 0, errmsg: '', data: item }; } catch (error) { throw error; } } async update({ id, name }) { 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 }); 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 content = await this.content.findOne({ bind: res.code }); const menu = await this.menu.findOne({ column: res.code }); const imgnews = await this.imgnews.findOne({ column: res.code }); if (content || menu || imgnews) { let errmsg = ''; if (content) errmsg += '(内容)'; if (menu) errmsg += '(菜单)'; if (imgnews) errmsg += '(图片新闻)'; return { errcode: -1001, errmsg: `存在${errmsg}绑定关系,不能删除`, data: '' }; } await this.model.remove({ _id: id }); return { errcode: 0, errmsg: '', data: 'delete' }; } catch (error) { throw error; } } async query({ skip, limit, code, name }) { const filter = {}; if (name || code) filter.$or = []; if (code) filter.$or.push({ code: { $regex: code } }); if (name) filter.$or.push({ name: { $regex: name } }); 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)); } else { res = await this.model.find({ ...filter }); } return { errcode: 0, errmsg: '', data: res, total: total.length }; } catch (error) { throw error; } } } module.exports = ColumnService;