user.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. // 用户管理
  5. class UserService extends CrudService {
  6. constructor(ctx) {
  7. super(ctx, 'user');
  8. this.model = this.ctx.model.User.User;
  9. this.studentModel = this.ctx.model.User.Student;
  10. this.schoolModel = this.ctx.model.User.School;
  11. this.coachModel = this.ctx.model.User.Coach;
  12. }
  13. /**
  14. * 检查数据重复
  15. */
  16. async createCheck() {
  17. const data = this.ctx.request.body;
  18. const { card, phone, openid } = data;
  19. let num = await this.model.count({ card });
  20. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该身份证号已被注册');
  21. num = await this.model.count({ phone });
  22. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该手机号码已被注册');
  23. num = await this.model.count({ openid });
  24. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该微信号码已被注册');
  25. return true;
  26. }
  27. /**
  28. * 微信小程序登录
  29. * @param {String} openid 微信小程序的openid
  30. */
  31. async wxAppLogin({ openid }) {
  32. const user = await this.model.findOne({ openid });
  33. // 没注册的需要手动注册
  34. if (!user) return user;
  35. const { type, _id } = user;
  36. // 超级管理员,普通用户,游客不需要其他信息,user里的就是
  37. if ([ '-1', '0', '10' ].includes(type)) return user;
  38. let infoModel;
  39. if (type === '1') infoModel = this.schoolModel;
  40. else if (type === '2') infoModel = this.coachModel;
  41. else if (type === '3') infoModel = this.studentModel;
  42. else throw new BusinessError(ErrorCode.USER_NOT_EXIST, '无法确定该用户的角色');
  43. const info = await infoModel.findOne({ user_id: _id });
  44. return { ...JSON.parse(JSON.stringify(user)), info };
  45. }
  46. }
  47. module.exports = UserService;