import { Role , SSEQueueResponse } from '@koh/common' ; import { Injectable } from '@nestjs/common' ; import { Response } from 'express' ; import { throttle } from 'lodash' ; import { SSEService } from 'sse/sse.service' ; import { QueueService } from './queue.service' ; type QueueClientMetadata = { userId : number ; role : Role ; } ; const idToRoom = ( queueId ) => `q-${ queueId }` ; /**
 * Handle sending queue sse events
 */ @ Injectable ( ) export class QueueSSEService { constructor ( private queueService , private sseService ) { } subscribeClient ( queueId , res , metadata ) { this . sseService . subscribeClient ( idToRoom ( queueId ) , res , metadata ) ; } updateQuestions = this . throttleUpdate ( async ( queueId ) => { const questions = await this . queueService . getQuestions ( queueId ) ; if ( questions ) { this . sendToRoom ( queueId , async ( { role , userId } ) => ( { questions : await this . queueService . personalizeQuestions ( queueId , questions , userId , role ) , } ) ) ; } } ) ; updateQueue = this . throttleUpdate ( async ( queueId ) => { const queue = await this . queueService . getQueue ( queueId ) ; if ( queue ) { await this . sendToRoom ( queueId , async ( ) => ( { queue } ) ) ; } } ) ; private async sendToRoom ( queueId , data ) { await this . sseService . sendEvent ( idToRoom ( queueId ) , data ) ; } private throttleUpdate ( updateFunction ) { return throttle ( async ( queueId ) => { try { await updateFunction ( queueId ) ; } catch ( e ) { } } , 1000 , { leading : false , trailing : true , } ) ; } }