market.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class MarketService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Market;
  8. }
  9. async create({ name, type, bindId, status, money, integral }) {
  10. assert(name, '商品名称不存在');
  11. assert(type, '商品类型不存在');
  12. assert(bindId, '货品ID不存在');
  13. assert(status, '商品状态不存在');
  14. assert(money, '价格不存在');
  15. try {
  16. const res = await this.model.create({ name, type, bindId, status, money, integral });
  17. return { errcode: 0, errmsg: 'ok', data: res };
  18. } catch (error) {
  19. throw error;
  20. }
  21. }
  22. async update({ id, name, type, bindId, status, money, integral }) {
  23. assert(id, 'id不存在');
  24. try {
  25. await this.model.updateOne({ _id: id }, { name, type, bindId, status, money, integral });
  26. return { errcode: 0, errmsg: 'ok', data: '' };
  27. } catch (error) {
  28. throw error;
  29. }
  30. }
  31. async delete({ id }) {
  32. assert(id, 'id不存在');
  33. try {
  34. await this.model.deleteOne({ _id: id });
  35. return { errcode: 0, errmsg: 'ok', data: '' };
  36. } catch (error) {
  37. throw error;
  38. }
  39. }
  40. async query({ skip, limit, name, type, bindId, status, money, integral }) {
  41. const filter = {};
  42. const arr = { name, type, bindId, status, money, integral };
  43. for (const e in arr) {
  44. const data = `{ "${e}": { "$regex": "${arr[e]}" } }`;
  45. if (arr[e]) {
  46. filter.$or = [];
  47. filter.$or.push(JSON.parse(data));
  48. }
  49. }
  50. try {
  51. const total = await this.model.find({ ...filter });
  52. let res;
  53. if (skip && limit) {
  54. res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  55. } else {
  56. res = await this.model.find({ ...filter });
  57. }
  58. return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
  59. } catch (error) {
  60. throw error;
  61. }
  62. }
  63. }
  64. module.exports = MarketService;