1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- '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');
- const Transaction = require('mongoose-transactions');
- //
- class RelationCoachSchoolService extends CrudService {
- constructor(ctx) {
- super(ctx, 'relationcoachschool');
- this.model = this.ctx.model.Relation.RelationCoachSchool;
- this.coachModel = this.ctx.model.User.Coach;
- this.tran = new Transaction();
- }
- // 创建关系前,先查下有没有,有就别创建了
- async beforeCreate(data) {
- const { coach_id, school_id } = data;
- const num = await this.model.count({ coach_id, school_id });
- if (num <= 0) {
- return data;
- }
- throw new BusinessError(ErrorCode.DATA_EXISTED, '教练已在学校备案,无需重复添加');
- }
- async afterQuery(filter, data) {
- data = JSON.parse(JSON.stringify(data));
- return data;
- }
- // 删除关系,同时将用户变为不同用户
- async delete(filter) {
- assert(filter);
- filter = await this.beforeDelete(filter);
- const { _id, id } = filter;
- try {
- const data = await this.model.findById(_id || id);
- if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到要删除的数据');
- const { coach_id } = data;
- const coach = await this.coachModel.findById(coach_id);
- const { user_id } = coach;
- this.tran.remove('RelationCoachSchool', _id || id);
- this.tran.remove('Coach', coach_id);
- this.tran.update('User', user_id, { type: '0' });
- await this.tran.run();
- } catch (error) {
- await this.tran.rollback();
- throw new Error(error);
- } finally {
- this.tran.clean();
- }
- return 'deleted';
- }
- }
- module.exports = RelationCoachSchoolService;
|