'use strict'; const assert = require('assert'); const _ = require('lodash'); const { ObjectId } = require('mongoose').Types; const { CrudService } = require('naf-framework-mongoose/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; class LiveroomService extends CrudService { constructor(ctx) { super(ctx, 'liveroom'); this.model = this.ctx.model.Liveroom; } async create(data) { const { subid, teacherid } = data; assert(subid, '缺少科目信息'); assert(teacherid, '缺少教师信息'); const list = await this.model.find(); const last = _.last(list); let number = '000001'; if (last) { number = last.number * 1 + 1; } data.number = number; const res = await this.model.create(data); return res; } async personcount(data) { const { number, name, userid, type } = data; // 取出已经进入直播的用户列表 // await this.app.redis.del(`liveroom${number}`); let list = await this.app.redis.get(`liveroom${number}`); if (!userid) return list; if (list) { // 已经开始直播,并且有人观看 list = JSON.parse(list); } else { // 还没有人进直播 list = []; } if (!type) { list.push({ name, userid, number }); } else { list = list.filter(f => f.userid !== userid); } list = _.uniqBy(list, 'userid'); await this.app.redis.set(`liveroom${number}`, JSON.stringify(list)); const { mq } = this.ctx; if (mq) { const exchange = 'liveroom-personcount'; const parm = { durable: true, headers: { userid: 1, }, }; await mq.fanout(exchange, number, list, parm); } return list; } } module.exports = LiveroomService;