Expose api.disconnect() (#664)

* Expose api.disconnect()

* Noop for non-WS disconnects
This commit is contained in:
Jaco Greeff
2019-02-08 16:32:38 +02:00
committed by GitHub
parent b122f0cde0
commit a2f863c56b
6 changed files with 45 additions and 1 deletions
+7
View File
@@ -56,6 +56,13 @@ export default class HttpProvider implements ProviderInterface {
return false;
}
/**
* @description Manually disconnect from the connection
*/
disconnect (): void {
// noop
}
/**
* @summary Whether the node is connected or not.
* @return {boolean} true if connected
+4
View File
@@ -75,6 +75,10 @@ export default class Mock implements ProviderInterface {
return true;
}
disconnect (): void {
// noop
}
isConnected (): boolean {
return true;
}
+1
View File
@@ -43,6 +43,7 @@ export type ProviderInterface$EmitCb = (value?: any) => any;
export interface ProviderInterface {
readonly hasSubscriptions: boolean;
disconnect (): void;
isConnected (): boolean;
on (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void;
send (method: string, params: Array<any>): Promise<any>;
+19 -1
View File
@@ -120,6 +120,22 @@ export default class WsProvider implements WSProviderInterface {
}
}
/**
* @description Manually disconnect from the connection, clearing autoconnect logic
*/
disconnect (): void {
if (isNull(this.websocket)) {
throw new Error('Cannot disconnect on a non-open websocket');
}
// switch off autoConnect, we are in manual mode now
this.autoConnect = false;
// 1000 - Normal closure; the connection successfully completed
this.websocket.close(1000);
this.websocket = null;
}
/**
* @summary Whether the node is connected or not.
* @return {boolean} true if connected
@@ -231,7 +247,9 @@ export default class WsProvider implements WSProviderInterface {
}
private onSocketClose = (event: CloseEvent): void => {
l.error(`disconnected from ${this.endpoint}::${event.code}: ${event.reason}`);
if (this.autoConnect) {
l.error(`disconnected from ${this.endpoint}::${event.code}: ${event.reason}`);
}
this._isConnected = false;
this.emit('disconnected');