relationCoachSchool.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. const Transaction = require('mongoose-transactions');
  7. //
  8. class RelationCoachSchoolService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'relationcoachschool');
  11. this.model = this.ctx.model.Relation.RelationCoachSchool;
  12. this.coachModel = this.ctx.model.User.Coach;
  13. this.tran = new Transaction();
  14. }
  15. // 创建关系前,先查下有没有,有就别创建了
  16. async beforeCreate(data) {
  17. const { coach_id, school_id } = data;
  18. const num = await this.model.count({ coach_id, school_id });
  19. if (num <= 0) {
  20. return data;
  21. }
  22. throw new BusinessError(ErrorCode.DATA_EXISTED, '教练已在学校备案,无需重复添加');
  23. }
  24. async afterQuery(filter, data) {
  25. data = JSON.parse(JSON.stringify(data));
  26. return data;
  27. }
  28. // 删除关系,同时将用户变为不同用户
  29. async delete(filter) {
  30. assert(filter);
  31. filter = await this.beforeDelete(filter);
  32. const { _id, id } = filter;
  33. try {
  34. const data = await this.model.findById(_id || id);
  35. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到要删除的数据');
  36. const { coach_id } = data;
  37. const coach = await this.coachModel.findById(coach_id);
  38. const { user_id } = coach;
  39. this.tran.remove('RelationCoachSchool', _id || id);
  40. this.tran.remove('Coach', coach_id);
  41. this.tran.update('User', user_id, { type: '0' });
  42. await this.tran.run();
  43. } catch (error) {
  44. await this.tran.rollback();
  45. throw new Error(error);
  46. } finally {
  47. this.tran.clean();
  48. }
  49. return 'deleted';
  50. }
  51. }
  52. module.exports = RelationCoachSchoolService;