format import { ClientResponseType } from 'flipper-common' ; import WebSocket from 'ws' ; import { WSCloseCode } from '../utils/WSCloseCode' ; import { ClientConnection , ConnectionStatus , ConnectionStatusChange , PendingRequestResolvers , } from './ClientConnection' ; export default class WebSocketClientConnection implements ClientConnection { protected pendingRequests : Map < number , PendingRequestResolvers > = new Map ( ) ; constructor ( protected ws ) { } subscribeToEvents ( subscriber ) { this . ws . on ( 'close' , ( ) => subscriber ( ConnectionStatus . CLOSED ) ) ; this . ws . on ( 'error' , ( ) => subscriber ( ConnectionStatus . ERROR ) ) ; } close ( ) { this . ws . close ( WSCloseCode . NormalClosure ) ; } send ( data ) { this . ws . send ( this . serializeData ( data ) ) ; } sendExpectResponse ( data ) { return new Promise ( ( resolve , reject ) => { this . pendingRequests . set ( data . id , { reject , resolve } ) ; this . ws . send ( this . serializeData ( data ) ) ; } ) ; } matchPendingRequest ( id ) { const callbacks = this . pendingRequests . get ( id ) ; if ( ! callbacks ) { console . debug ( `[conn] Pending request ${ id } is not found. Ignore.` ) ; return ; } this . pendingRequests . delete ( id ) ; return callbacks ; } protected serializeData ( data ) { return JSON . stringify ( data ) ; } }