Skip to content

Commit

Permalink
Add onConnectionFailure callback
Browse files Browse the repository at this point in the history
  • Loading branch information
syyyr committed Sep 11, 2024
1 parent bfd341c commit cb93f86
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "libshv-js",
"version": "3.3.3",
"version": "3.3.4",
"description": "Typescript implementation of libshv",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
Expand Down
19 changes: 17 additions & 2 deletions src/ws-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ type WsClientOptions = {
timeout?: number;
wsUri: string;
onConnected: () => void;
onConnectionFailure: (error: Error) => void;
onDisconnected: () => void;
onRequest: (rpc_msg: RpcMessage) => void;
};
Expand Down Expand Up @@ -87,6 +88,7 @@ class WsClient {
password: WsClientOptions['password'];
loginType: WsClientOptions['loginType'];
onConnected: WsClientOptions['onConnected'];
onConnectionFailure: WsClientOptions['onConnectionFailure'];
onDisconnected: WsClientOptions['onDisconnected'];
onRequest: WsClientOptions['onRequest'];
timeout: WsClientOptions['timeout'];
Expand All @@ -107,14 +109,23 @@ class WsClient {
this.websocket.binaryType = 'arraybuffer';

this.onConnected = options.onConnected ?? (() => {/* nothing */});
this.onConnectionFailure = options.onConnectionFailure ?? (() => {/* nothing */});
this.onDisconnected = options.onDisconnected ?? (() => {/* nothing */});
this.onRequest = options.onRequest ?? (() => {/* nothing */});

this.timeout = options.timeout ?? DEFAULT_TIMEOUT;

this.websocket.addEventListener('open', () => {
this.logDebug('CONNECTED');
this.callRpcMethod(undefined, 'hello').then(() => {
const handleConnectionError = (error: Error) => {
this.logDebug('FAILURE: couldn\'t perform initial handshake', error.message);
this.onConnectionFailure(error);
};
this.callRpcMethod(undefined, 'hello').then(response => {
if (response instanceof Error) {
handleConnectionError(response);
return;
}
const params = makeMap({
login: makeMap({
password: this.password,
Expand All @@ -126,7 +137,11 @@ class WsClient {
}),
});
return this.callRpcMethod(undefined, 'login', params);
}).then(() => {
}).then(response => {
if (response instanceof Error) {
handleConnectionError(response);
return;
}
this.logDebug('SUCCESS: connected to shv broker');
this.onConnected();
}).catch(() => {
Expand Down

0 comments on commit cb93f86

Please sign in to comment.