diff --git a/src/core/RPCConnection.ts b/src/core/RPCConnection.ts index e12e833..8e30261 100644 --- a/src/core/RPCConnection.ts +++ b/src/core/RPCConnection.ts @@ -14,18 +14,31 @@ interface RPCConnectionEvents { closed: void; } +class CallResponseEmitter extends EventEmitter<{ + [id: string]: RPCPacket; +}> { + emitAll(packet: RPCPacket) { + this.events.forEach(subscribers => { + subscribers.forEach(fn => fn(packet)); + }) + } +} + export class RPCConnection extends EventEmitter { closed: boolean = false; - private callResponseEmitter = new EventEmitter<{ - [id: string]: RPCPacket; - }>(); + private callResponseEmitter = new CallResponseEmitter(); constructor(public socket: SocketConnection) { super(); socket.on('closed', () => { this.emit('closed'); + this.callResponseEmitter.emitAll(makeCallResponsePacket({ + status: 'error', + requestPacketId: 'connection error', + errorCode: RPCErrorCode.CONNECTION_DISCONNECTED, + })); this.callResponseEmitter.removeAllListeners(); this.closed = true; }); @@ -68,6 +81,12 @@ export class RPCConnection extends EventEmitter { args: any[]; timeout: number; }): Promise { + if (this.closed) { + throw new RPCError({ + errorCode: RPCErrorCode.CONNECTION_DISCONNECTED, + }); + } + const { fnPath, args } = options; const packet = makeCallPacket({ fnPath, diff --git a/src/core/RPCError.ts b/src/core/RPCError.ts index b6e6b2f..9f80c70 100644 --- a/src/core/RPCError.ts +++ b/src/core/RPCError.ts @@ -9,6 +9,7 @@ export enum RPCErrorCode { HANDSHAKE_INCOMPLETE = -400, TIMEOUT_ERROR = -500, CALL_PROTOCOL_ERROR = -600, + CONNECTION_DISCONNECTED = -700, } export const RPC_ERROR_MESSAGES: Record = { @@ -22,6 +23,7 @@ export const RPC_ERROR_MESSAGES: Record = { [RPCErrorCode.HANDSHAKE_INCOMPLETE]: 'Handshake not completed', [RPCErrorCode.TIMEOUT_ERROR]: 'Request timeout', [RPCErrorCode.CALL_PROTOCOL_ERROR]: 'Call protocol error', + [RPCErrorCode.CONNECTION_DISCONNECTED]: 'Connection disconnected', } as const; export class RPCError extends Error { diff --git a/src/utils/EventEmitter.ts b/src/utils/EventEmitter.ts index acce398..7fe85c9 100644 --- a/src/utils/EventEmitter.ts +++ b/src/utils/EventEmitter.ts @@ -2,7 +2,7 @@ type EventType = Record; export class BaseEventEmitter { - private events: Map void>> = new Map(); + protected events: Map void>> = new Map(); public on(event: K, listener: (args: T[K]) => void) { this.addListener({ event, listener });