address.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. return data;
  18. }
  19. /**
  20. * 如果数据是第一条数据,则地址为默认地址
  21. * @param {Object} data 地址参数
  22. */
  23. async beforeCreate(data) {
  24. const { customer } = data;
  25. const num = await this.model.count({ customer });
  26. if (num <= 0) data.is_default = '1';
  27. return data;
  28. }
  29. async toDefault({ id }) {
  30. const data = await this.model.findById(id);
  31. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  32. const { customer } = data;
  33. await this.model.updateMany({ customer }, { is_default: this.defaultValue });
  34. await this.model.updateOne({ _id: id }, { is_default: '1' });
  35. }
  36. }
  37. module.exports = AddressService;