liveroom.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. list = JSON.stringify(list);
  46. await this.app.redis.set(`liveroom${number}`, list);
  47. const { mq } = this.ctx;
  48. if (mq) {
  49. const exchange = 'liveroom-personcount';
  50. const parm = {
  51. durable: true,
  52. headers: {
  53. userid: 1,
  54. },
  55. };
  56. await mq.fanout(exchange, number, list, parm);
  57. }
  58. return list;
  59. }
  60. }
  61. module.exports = LiveroomService;