liveroom.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 LiveroomService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'liveroom');
  10. this.model = this.ctx.model.Liveroom;
  11. }
  12. async create(data) {
  13. const { subid, teacherid } = data;
  14. assert(subid, '缺少科目信息');
  15. assert(teacherid, '缺少教师信息');
  16. const list = await this.model.find();
  17. const last = _.last(list);
  18. let number = '000001';
  19. if (last) {
  20. number = last.number * 1 + 1;
  21. }
  22. data.number = number;
  23. const res = await this.model.create(data);
  24. return res;
  25. }
  26. async personcount(data) {
  27. const { number, name, userid, type } = data;
  28. // 取出已经进入直播的用户列表
  29. // await this.app.redis.del(`liveroom${number}`);
  30. let list = await this.app.redis.get(`liveroom${number}`);
  31. if (!userid) return list;
  32. if (list) {
  33. // 已经开始直播,并且有人观看
  34. list = JSON.parse(list);
  35. } else {
  36. // 还没有人进直播
  37. list = [];
  38. }
  39. if (!type) {
  40. list.push({ name, userid, number });
  41. } else {
  42. list = list.filter(f => f.userid !== userid);
  43. }
  44. list = _.uniqBy(list, 'userid');
  45. await this.app.redis.set(`liveroom${number}`, JSON.stringify(list));
  46. const { mq } = this.ctx;
  47. if (mq) {
  48. const exchange = 'liveroom-personcount';
  49. const parm = {
  50. durable: true,
  51. headers: {
  52. userid: 1,
  53. },
  54. };
  55. await mq.fanout(exchange, number, list, parm);
  56. }
  57. return list;
  58. }
  59. }
  60. module.exports = LiveroomService;