1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- '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 UserService extends CrudService {
- constructor(ctx) {
- super(ctx, 'user');
- this.model = this.ctx.model.Race.User;
- this.baseUserModel = this.ctx.model.Base.User;
- this.baseCoachModel = this.ctx.model.Base.Coach;
- }
- async login({ openid }) {
- const num = await this.model.count({ openid });
- if (num <= 0) {
- // 去找基础库找用户,然后将信息拿来
- const user = await this.baseUserModel.findOne({ openid });
- if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST, '用户不存在,无法进入比赛系统');
- const { _id: user_id, type } = user;
- const obj = { openid, user_id };
- if (type === '0' || type === '3' || type === '2') obj.type = '0';
- else obj.type = type;
- await this.create(obj);
- }
- const list = await this.query({ openid });
- return _.head(list);
- }
- async beforeCreate(body) {
- const { openid, user_id } = body;
- const num = await this.model.count({ openid, user_id });
- if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '比赛模块已有该用户信息');
- return body;
- }
- /**
- * 根据传来的数据,以openid为唯一条件进行查询,如果有用户,则覆盖.没有用户则创建
- * @param {Object} body 参数体
- */
- async bindJudge(body) {
- const { openid } = body;
- const num = await this.model.count({ openid });
- if (num > 0) await this.model.update({ openid }, body);
- else await this.model.create(body);
- return await this.model.findOne({ openid });
- }
- // 教练成为裁判
- async coachToBeJudge({ coach_id, parent_id }) {
- const coach = await this.baseCoachModel.findById(coach_id);
- if (!coach) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到教练信息');
- const { user_id } = coach;
- // user_id: 基础模块 的 用户表 数据id
- return await this.userToBeJudge({ user_id, parent_id });
- }
- // 用户成为裁判
- async userToBeJudge({ user_id, parent_id }) {
- assert(user_id, '缺少裁判用户信息');
- assert(parent_id, '缺少赛事创建方信息');
- const user = await this.baseUserModel.findById(user_id);
- if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST, '未找到基础模块用户信息');
- const { openid } = user;
- const obj = { user_id, parent_id, type: '2', openid };
- return this.bindJudge(obj);
- }
- }
- module.exports = UserService;
|