user.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. async fetch({ openid }) {
  14. const res = await this.model.findOne({ openid });
  15. return res;
  16. }
  17. /**
  18. * 检查数据重复
  19. */
  20. async createCheck() {
  21. const data = this.ctx.request.body;
  22. const { card, phone, openid } = data;
  23. let num = await this.model.count({ card });
  24. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该身份证号已被注册');
  25. num = await this.model.count({ phone });
  26. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该手机号码已被注册');
  27. num = await this.model.count({ openid });
  28. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该微信号码已被注册');
  29. return true;
  30. }
  31. /**
  32. * 微信小程序登录
  33. * @param {String} openid 微信小程序的openid
  34. */
  35. async wxAppLogin({ openid }) {
  36. const user = await this.model.findOne({ openid });
  37. // 没注册的需要手动注册
  38. if (!user) return user;
  39. const { type, _id } = user;
  40. // 超级管理员,普通用户,游客不需要其他信息,user里的就是
  41. if ([ '-1', '0', '10' ].includes(type)) return user;
  42. let infoModel;
  43. if (type === '1') infoModel = this.schoolModel;
  44. else if (type === '2') infoModel = this.coachModel;
  45. else if (type === '3') infoModel = this.studentModel;
  46. else throw new BusinessError(ErrorCode.USER_NOT_EXIST, '无法确定该用户的角色');
  47. const info = await infoModel.findOne({ user_id: _id });
  48. return { ...JSON.parse(JSON.stringify(user)), info };
  49. }
  50. }
  51. module.exports = UserService;