market.js 2.1 KB

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