goodsSet.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const { ObjectId } = require('mongoose').Types;
  7. //
  8. class GoodsSetService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'goodsset');
  11. this.model = this.ctx.model.Shop.GoodsSet;
  12. this.goodsModel = this.ctx.model.Shop.Goods;
  13. this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
  14. }
  15. async update(filter, update, { projection } = {}) {
  16. assert(filter);
  17. assert(update);
  18. const beforeUpdateResult = await this.beforeUpdate(filter, update);
  19. filter = beforeUpdateResult.filter;
  20. update = beforeUpdateResult.update;
  21. const { _id, id } = filter;
  22. if (_id || id) filter = { _id: ObjectId(_id || id) };
  23. // TODO:检查数据是否存在
  24. const entity = await this.model.findOne(filter).exec();
  25. if (!entity) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  26. await this.model.updateOne(filter, update);
  27. let reSearchData = await this.model.findOne(filter, projection).exec();
  28. reSearchData = await this.afterUpdate(filter, update, reSearchData);
  29. return reSearchData;
  30. }
  31. /**
  32. * 获取套装快照
  33. * @param id 套装id
  34. */
  35. async getSnapshot(id) {
  36. const data = await this.model.findById(id).lean();
  37. const { set = [] } = data;
  38. for (const s of set) {
  39. const { goods, spec } = s;
  40. const goodsData = await this.goodsModel.findById(goods).lean();
  41. const goodsSpecData = await this.goodsSpecModel.findById(spec).lean();
  42. s.spec = goodsSpecData;
  43. s.goods = goodsData;
  44. }
  45. // 换成goods
  46. data.goods = set;
  47. delete data.set;
  48. delete data._id;
  49. return data;
  50. }
  51. }
  52. module.exports = GoodsSetService;