'use strict'; const assert = require('assert'); const Service = require('egg').Service; class ImgtypeService extends Service { constructor(ctx) { super(ctx); this.model = this.ctx.model.Imgtype; 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 imgnews = await this.imgnews.findOne({ bind: res.code }); if (imgnews) 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 }) { const filter = {}; if (name || code) filter.$or = []; if (name) filter.$or.push({ code: { $regex: name } }); if (code) filter.$or.push({ name: { $regex: code } }); 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 = ImgtypeService;