address.js 1.1 KB

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