goods.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class GoodsService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Goods;
  8. }
  9. async create({ name, describe, content, thumbnail }) {
  10. assert(name, '货物名称不存在');
  11. assert(describe, '货物类型不存在');
  12. assert(content, '货物内容不存在');
  13. assert(thumbnail, '货物展示图不存在');
  14. try {
  15. const res = await this.model.create({ name, describe, content, thumbnail });
  16. return { errcode: 0, errmsg: 'ok', data: res };
  17. } catch (error) {
  18. throw error;
  19. }
  20. }
  21. async update({ id, name, describe, content, thumbnail }) {
  22. assert(id, 'id不存在');
  23. try {
  24. await this.model.updateOne({ _id: id }, { name, describe, content, thumbnail });
  25. return { errcode: 0, errmsg: 'ok', data: '' };
  26. } catch (error) {
  27. throw error;
  28. }
  29. }
  30. async delete({ id }) {
  31. assert(id, 'id不存在');
  32. try {
  33. await this.model.deleteOne({ _id: id });
  34. return { errcode: 0, errmsg: 'ok', data: '' };
  35. } catch (error) {
  36. throw error;
  37. }
  38. }
  39. async query({ skip, limit, name, describe, content, thumbnail }) {
  40. const filter = {};
  41. const arr = { name, describe, content, thumbnail };
  42. for (const e in arr) {
  43. const data = `{ "${e}": { "$regex": "${arr[e]}" } }`;
  44. if (arr[e]) {
  45. filter.$or = [];
  46. filter.$or.push(JSON.parse(data));
  47. }
  48. }
  49. try {
  50. const total = await this.model.find({ ...filter });
  51. let res;
  52. if (skip && limit) {
  53. res = await this.model.find({ ...filter }, { content: false }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  54. } else {
  55. res = await this.model.find({ ...filter }, { content: false });
  56. }
  57. return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
  58. } catch (error) {
  59. throw error;
  60. }
  61. }
  62. async fetch({ id }) {
  63. try {
  64. const res = await this.model.findOne({ _id: id });
  65. if (!res) return { errcode: -1001, errmsg: '数据不存在', data: '' };
  66. return { errcode: 0, errmsg: '', data: res };
  67. } catch (error) {
  68. throw error;
  69. }
  70. }
  71. }
  72. module.exports = GoodsService;