1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- 'use strict';
- const assert = require('assert');
- const Service = require('egg').Service;
- class GoodsService extends Service {
- constructor(ctx) {
- super(ctx);
- this.model = this.ctx.model.Goods;
- }
- async create({ name, describe, content, thumbnail }) {
- assert(name, '货物名称不存在');
- assert(describe, '货物类型不存在');
- assert(content, '货物内容不存在');
- assert(thumbnail, '货物展示图不存在');
- try {
- const res = await this.model.create({ name, describe, content, thumbnail });
- return { errcode: 0, errmsg: 'ok', data: res };
- } catch (error) {
- throw error;
- }
- }
- async update({ id, name, describe, content, thumbnail }) {
- assert(id, 'id不存在');
- try {
- await this.model.updateOne({ _id: id }, { name, describe, content, thumbnail });
- return { errcode: 0, errmsg: 'ok', data: '' };
- } catch (error) {
- throw error;
- }
- }
- async delete({ id }) {
- assert(id, 'id不存在');
- try {
- await this.model.deleteOne({ _id: id });
- return { errcode: 0, errmsg: 'ok', data: '' };
- } catch (error) {
- throw error;
- }
- }
- async query({ skip, limit, name, describe, content, thumbnail }) {
- const filter = {};
- const arr = { name, describe, content, thumbnail };
- for (const e in arr) {
- const data = `{ "${e}": { "$regex": "${arr[e]}" } }`;
- if (arr[e]) {
- filter.$or = [];
- filter.$or.push(JSON.parse(data));
- }
- }
- try {
- const total = await this.model.find({ ...filter });
- let res;
- if (skip && limit) {
- res = await this.model.find({ ...filter }, { content: false }).skip(Number(skip) * Number(limit)).limit(Number(limit));
- } else {
- res = await this.model.find({ ...filter }, { content: false });
- }
- return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
- } catch (error) {
- throw error;
- }
- }
- async fetch({ id }) {
- try {
- const res = await this.model.findOne({ _id: id });
- if (!res) return { errcode: -1001, errmsg: '数据不存在', data: '' };
- return { errcode: 0, errmsg: '', data: res };
- } catch (error) {
- throw error;
- }
- }
- }
- module.exports = GoodsService;
|