relationStudentSchool.js 1.7 KB

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