liveroom.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. let list = await this.app.redis.get(`liveroom${number}`);
  30. console.group('group');
  31. console.table(list);
  32. console.groupEnd();
  33. if (list) {
  34. // // 已经开始直播,并且有人观看
  35. list = JSON.parse(list);
  36. } else {
  37. // 还没有人进直播
  38. list = [{ name, userid }];
  39. }
  40. if (!type) {
  41. list.push({ name, userid, number });
  42. list = _.uniqBy(list, 'userid');
  43. } else {
  44. list = list.filter(f => f.userid !== userid);
  45. }
  46. console.group('group2');
  47. console.log(JSON.parse(list));
  48. console.groupEnd();
  49. await this.app.redis.set(`liveroom${number}`, JSON.parse(list));
  50. const { mq } = this.ctx;
  51. if (mq) {
  52. const exchange = 'liveroom-personcount';
  53. const parm = {
  54. durable: true,
  55. headers: {
  56. userid: 1,
  57. },
  58. };
  59. await mq.fanout(exchange, number, list, parm);
  60. }
  61. }
  62. }
  63. module.exports = LiveroomService;