user.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. //
  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. }
  13. async login({ openid }) {
  14. const num = await this.model.count({ openid });
  15. if (num <= 0) {
  16. // 去找基础库找用户,然后将信息拿来
  17. const user = await this.baseUserModel.findOne({ openid });
  18. if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST, '用户不存在,无法进入比赛系统');
  19. const { _id: user_id, type } = user;
  20. const obj = { openid, user_id };
  21. if (type === '0' || type === '3' || type === '2') obj.type = '0';
  22. else obj.type = type;
  23. await this.create(obj);
  24. }
  25. const list = await this.query({ openid });
  26. return _.head(list);
  27. }
  28. async beforeCreate(body) {
  29. const { openid, user_id } = body;
  30. const num = await this.model.count({ openid, user_id });
  31. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '比赛模块已有该用户信息');
  32. return body;
  33. }
  34. /**
  35. * 根据传来的数据,以openid为唯一条件进行查询,如果有用户,则覆盖.没有用户则创建
  36. * @param {Object} body 参数体
  37. */
  38. async bindJudge(body) {
  39. const { openid } = body;
  40. const num = await this.model.count({ openid });
  41. if (num > 0) await this.model.update({ openid }, body);
  42. else await this.model.create(body);
  43. return await this.model.findOne({ openid });
  44. }
  45. }
  46. module.exports = UserService;