import { MessageType } from "../../../enums" ; import { IClient } from "../../../models/client" ; import { IMessage } from "../../../models/message" ; import { IRealm } from "../../../models/realm" ; export const TransmissionHandler = ( { realm } ) : ( client : IClient | undefined , message : IMessage ) => boolean => { const handle = ( client , message ) => { const type = message . type ; const srcId = message . src ; const dstId = message . dst ; const destinationClient = realm . getClientById ( dstId ) ; if ( destinationClient ) { const socket = destinationClient . getSocket ( ) ; try { if ( socket ) { const data = JSON . stringify ( message ) ; socket . send ( data ) ; } else { throw new Error ( "Peer dead" ) ; } } catch ( e ) { if ( socket ) { socket . close ( ) ; } else { realm . removeClientById ( destinationClient . getId ( ) ) ; } handle ( client , { type : MessageType . LEAVE , src : dstId , dst : srcId } ) ; } } else { const ignoredTypes = [ MessageType . LEAVE , MessageType . EXPIRE ] ; if ( ! ignoredTypes . includes ( type ) && dstId ) { realm . addMessageToQueue ( dstId , message ) ; } else if ( type === MessageType . LEAVE && ! dstId ) { realm . removeClientById ( srcId ) ; } else { } } return true ; } ; return handle ; } ;