address.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. //
  7. class AddressService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'address');
  10. this.model = this.ctx.model.User.Address;
  11. // 默认值.为:非默认
  12. this.defaultValue = '0';
  13. }
  14. async afterCreate(body, data) {
  15. const { is_default } = data;
  16. if (is_default !== this.defaultValue) await this.toDefault({ id: data._id });
  17. await this.checkDefault({ customer: data.customer });
  18. return data;
  19. }
  20. /**
  21. * 如果数据是第一条数据,则地址为默认地址
  22. * @param {Object} data 地址参数
  23. */
  24. async beforeCreate(data) {
  25. const { customer } = data;
  26. const num = await this.model.count({ customer });
  27. if (num <= 0) data.is_default = '1';
  28. return data;
  29. }
  30. async afterUpdate(filter, body, data) {
  31. if (data.is_default !== this.defaultValue) await this.toDefault({ id: data._id });
  32. await this.checkDefault({ customer: data.customer });
  33. return data;
  34. }
  35. async toDefault({ id }) {
  36. const data = await this.model.findById(id);
  37. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  38. const { customer } = data;
  39. await this.model.updateMany({ customer }, { is_default: this.defaultValue });
  40. await this.model.updateOne({ _id: id }, { is_default: '1' });
  41. }
  42. /**
  43. * 确认用户有默认地址
  44. * @param {Object} params 参数
  45. * @param params.customer 用户id
  46. */
  47. async checkDefault({ customer }) {
  48. const num = await this.model.count({ customer, is_default: '1' });
  49. if (num > 0) return;
  50. const data = await this.model.findOne({ customer });
  51. if (data) await this.model.updateOne({ _id: data._id }, { is_default: '1' });
  52. }
  53. }
  54. module.exports = AddressService;