address.js 955 B

12345678910111213141516171819202122232425262728293031
  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. async toDefault({ id }) {
  20. const data = await this.model.findById(id);
  21. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  22. const { customer } = data;
  23. await this.model.updateMany({ customer }, { is_default: this.defaultValue });
  24. await this.model.updateOne({ _id: id }, { is_default: '1' });
  25. }
  26. }
  27. module.exports = AddressService;