channel.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { ObjectId } = require('mongoose').Types;
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. class ChannelService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'channel');
  10. this.model = this.ctx.model.Channel;
  11. }
  12. async create(data) {
  13. const { user_id, title, orgin, type } = data;
  14. assert(user_id, '缺少创建人信息');
  15. assert(title, '缺少标题');
  16. assert(orgin, '缺少来源');
  17. assert(type, '缺少类别');
  18. const last = await this.model.findOne().sort({ room_id: -1 });
  19. if (last) {
  20. const { room_id } = last;
  21. if (parseInt(room_id)) data.room_id = `${parseInt(room_id) + 1}`;
  22. else data.room_id = `${room_id}1`;
  23. } else {
  24. data.room_id = '2001';
  25. }
  26. data.passwd = { secret: data.room_id };
  27. let res = await this.model.create(data);
  28. if (res) {
  29. res = JSON.parse(JSON.stringify(res));
  30. res.passwd = data.room_id;
  31. console.log(res);
  32. }
  33. return res;
  34. }
  35. async login(data) {
  36. const { room_id, passwd } = data;
  37. assert(room_id, '请填写房间号');
  38. assert(passwd, '请填写密码');
  39. let channel = await this.model.findOne({ room_id }, '+passwd');
  40. if (!channel) throw new BusinessError(ErrorCode.USER_NOT_EXIST, '房间号不存在');
  41. const secret = _.get(channel, 'passwd.secret');
  42. if (!secret) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '房间号密码缺失');
  43. if (passwd === secret) {
  44. channel = JSON.parse(JSON.stringify(channel));
  45. channel = _.omit(channel, [ 'passwd' ]);
  46. return channel;
  47. } throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
  48. }
  49. }
  50. module.exports = ChannelService;