import uuidv4 from "uuid/v4" ; import { IClient } from "./client" ; import { IMessage } from "./message" ; import { IMessageQueue , MessageQueue } from "./messageQueue" ; export interface IRealm { getClientsIds ( ) : string [ ] ; getClientById ( clientId ) : IClient | undefined ; getClientsIdsWithQueue ( ) : string [ ] ; setClient ( client , id ) : void ; removeClientById ( id ) : boolean ; getMessageQueueById ( id ) : IMessageQueue | undefined ; addMessageToQueue ( id , message ) : void ; clearMessageQueue ( id ) : void ; generateClientId ( generateClientId ? ) : string ; } export class Realm implements IRealm { private readonly clients : Map < string , IClient > = new Map ( ) ; private readonly messageQueues : Map < string , IMessageQueue > = new Map ( ) ; public getClientsIds ( ) { return [ ... this . clients . keys ( ) ] ; } public getClientById ( clientId ) { return this . clients . get ( clientId ) ; } public getClientsIdsWithQueue ( ) { return [ ... this . messageQueues . keys ( ) ] ; } public setClient ( client , id ) { this . clients . set ( id , client ) ; } public removeClientById ( id ) { const client = this . getClientById ( id ) ; if ( ! client ) return false ; this . clients . delete ( id ) ; return true ; } public getMessageQueueById ( id ) { return this . messageQueues . get ( id ) ; } public addMessageToQueue ( id , message ) { if ( ! this . getMessageQueueById ( id ) ) { this . messageQueues . set ( id , new MessageQueue ( ) ) ; } this . getMessageQueueById ( id ) ?. addMessage ( message ) ; } public clearMessageQueue ( id ) { this . messageQueues . delete ( id ) ; } public generateClientId ( generateClientId ? ) { const generateId = generateClientId ? generateClientId : uuidv4 ; let clientId = generateId ( ) ; while ( this . getClientById ( clientId ) ) { clientId = generateId ( ) ; } return clientId ; } }