1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- 'use strict';
- const assert = require('assert');
- const Service = require('egg').Service;
- class ToconfigService extends Service {
- constructor(ctx) {
- super(ctx);
- this.model = this.ctx.model.Toconfig;
- }
- async create({ name, code, type, value }) {
- assert(name, '名称不存在');
- assert(code, '编码不存在');
- assert(value, '值不存在');
- try {
- const res = await this.model.findOne({ code });
- if (res) return { errcode: -1001, errmsg: '编码已存在', data: '' };
- const item = await this.model.create({ name, code, type, value });
- return { errcode: 0, errmsg: '', data: item };
- } catch (error) {
- throw error;
- }
- }
- async update({ id, name, type, value }) {
- 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, type, value });
- 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: '' };
- 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({ name: { $regex: name } });
- if (code) filter.$or.push({ code: { $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 = ToconfigService;
|