12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- 'use strict';
- const { CrudService } = require('naf-framework-mongoose-free/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const _ = require('lodash');
- const assert = require('assert');
- //
- class AddressService extends CrudService {
- constructor(ctx) {
- super(ctx, 'address');
- this.model = this.ctx.model.User.Address;
- // 默认值.为:非默认
- this.defaultValue = '0';
- }
- async afterCreate(body, data) {
- const { is_default } = data;
- if (is_default !== this.defaultValue) await this.toDefault({ id: data._id });
- await this.checkDefault({ customer: data.customer });
- return data;
- }
- /**
- * 如果数据是第一条数据,则地址为默认地址
- * @param {Object} data 地址参数
- */
- async beforeCreate(data) {
- const { customer } = data;
- const num = await this.model.count({ customer });
- if (num <= 0) data.is_default = '1';
- return data;
- }
- async afterUpdate(filter, body, data) {
- if (data.is_default !== this.defaultValue) await this.toDefault({ id: data._id });
- await this.checkDefault({ customer: data.customer });
- return data;
- }
- async toDefault({ id }) {
- const data = await this.model.findById(id);
- if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
- const { customer } = data;
- await this.model.updateMany({ customer }, { is_default: this.defaultValue });
- await this.model.updateOne({ _id: id }, { is_default: '1' });
- }
- /**
- * 确认用户有默认地址
- * @param {Object} params 参数
- * @param params.customer 用户id
- */
- async checkDefault({ customer }) {
- const num = await this.model.count({ customer, is_default: '1' });
- if (num > 0) return;
- const data = await this.model.findOne({ customer });
- if (data) await this.model.updateOne({ _id: data._id }, { is_default: '1' });
- }
- }
- module.exports = AddressService;
|