user.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. }
  12. async login({ openid }) {
  13. const num = await this.model.count({ openid });
  14. if (num <= 0) return null;
  15. const list = await this.query({ openid });
  16. return _.head(list);
  17. }
  18. async beforeCreate(body) {
  19. const { openid, user_id } = body;
  20. const num = await this.model.count({ openid, user_id });
  21. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '比赛模块已有该用户信息');
  22. return body;
  23. }
  24. /**
  25. * 根据传来的数据,以openid为唯一条件进行查询,如果有用户,则覆盖.没有用户则创建
  26. * @param {Object} body 参数体
  27. */
  28. async bindJudge(body) {
  29. const { openid } = body;
  30. const num = await this.model.count({ openid });
  31. if (num > 0) await this.model.update({ openid }, body);
  32. else await this.model.create(body);
  33. return await this.model.findOne({ openid });
  34. }
  35. }
  36. module.exports = UserService;