user.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 UserService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'user');
  10. this.model = this.ctx.model.Race.User;
  11. this.baseUserModel = this.ctx.model.Base.User;
  12. this.baseCoachModel = this.ctx.model.Base.Coach;
  13. }
  14. async login({ openid }) {
  15. const num = await this.model.count({ openid });
  16. if (num <= 0) {
  17. // 去找基础库找用户,然后将信息拿来
  18. const user = await this.baseUserModel.findOne({ openid });
  19. if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST, '用户不存在,无法进入比赛系统');
  20. const { _id: user_id, type } = user;
  21. const obj = { openid, user_id };
  22. if (type === '0' || type === '3' || type === '2') obj.type = '0';
  23. else obj.type = type;
  24. await this.create(obj);
  25. }
  26. const list = await this.query({ openid });
  27. return _.head(list);
  28. }
  29. async beforeCreate(body) {
  30. const { openid, user_id } = body;
  31. const num = await this.model.count({ openid, user_id });
  32. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '比赛模块已有该用户信息');
  33. return body;
  34. }
  35. /**
  36. * 根据传来的数据,以openid为唯一条件进行查询,如果有用户,则覆盖.没有用户则创建
  37. * @param {Object} body 参数体
  38. */
  39. async bindJudge(body) {
  40. const { openid } = body;
  41. const num = await this.model.count({ openid });
  42. if (num > 0) await this.model.update({ openid }, body);
  43. else await this.model.create(body);
  44. return await this.model.findOne({ openid });
  45. }
  46. // 教练成为裁判
  47. async coachToBeJudge({ coach_id, parent_id }) {
  48. const coach = await this.baseCoachModel.findById(coach_id);
  49. if (!coach) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到教练信息');
  50. const { user_id } = coach;
  51. // user_id: 基础模块 的 用户表 数据id
  52. return await this.userToBeJudge({ user_id, parent_id });
  53. }
  54. // 用户成为裁判
  55. async userToBeJudge({ user_id, parent_id }) {
  56. assert(user_id, '缺少裁判用户信息');
  57. assert(parent_id, '缺少赛事创建方信息');
  58. const user = await this.baseUserModel.findById(user_id);
  59. if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST, '未找到基础模块用户信息');
  60. const { openid } = user;
  61. const obj = { user_id, parent_id, type: '2', openid };
  62. return this.bindJudge(obj);
  63. }
  64. }
  65. module.exports = UserService;