Add unsubscribe client method

This commit is contained in:
Riordan Panayides 2023-04-09 14:41:08 +01:00
parent dfd3cf8527
commit eb44c8fb4f
1 changed files with 22 additions and 6 deletions

View File

@ -1,12 +1,12 @@
import WebSocket from 'ws'; import WebSocket from 'ws';
interface FillsFeedOptions { interface FillsFeedOptions {
subscriptions?: FillsFeedSubscriptionParams; subscriptions?: FillsFeedSubscribeParams;
reconnectIntervalMs?: number; reconnectIntervalMs?: number;
reconnectionMaxAttempts?: number; reconnectionMaxAttempts?: number;
} }
interface FillsFeedSubscriptionParams { interface FillsFeedSubscribeParams {
marketId?: string; marketId?: string;
marketIds?: string[]; marketIds?: string[];
accountIds?: string[]; accountIds?: string[];
@ -67,7 +67,7 @@ function isStatusMessage(obj: any): obj is StatusMessage {
export class FillsFeed { export class FillsFeed {
private _url: string; private _url: string;
private _socket: WebSocket; private _socket: WebSocket;
private _subscriptions?: FillsFeedSubscriptionParams; private _subscriptions?: FillsFeedSubscribeParams;
private _connected: boolean; private _connected: boolean;
private _reconnectionIntervalMs; private _reconnectionIntervalMs;
private _reconnectionAttempts; private _reconnectionAttempts;
@ -90,7 +90,10 @@ export class FillsFeed {
} }
private _reconnectionAttemptsExhausted(): boolean { private _reconnectionAttemptsExhausted(): boolean {
return this._reconnectionMaxAttempts != -1 && this._reconnectionAttempts >= this._reconnectionMaxAttempts return (
this._reconnectionMaxAttempts != -1 &&
this._reconnectionAttempts >= this._reconnectionMaxAttempts
);
} }
private _connect() { private _connect() {
@ -99,7 +102,7 @@ export class FillsFeed {
this._socket.addEventListener('error', (err) => { this._socket.addEventListener('error', (err) => {
console.warn(`[FillsFeed] connection error: ${err.message}`); console.warn(`[FillsFeed] connection error: ${err.message}`);
if (this._reconnectionAttemptsExhausted()) { if (this._reconnectionAttemptsExhausted()) {
console.error('[FillsFeed] fatal connection error') console.error('[FillsFeed] fatal connection error');
throw err.error; throw err.error;
} }
}); });
@ -140,7 +143,7 @@ export class FillsFeed {
}); });
} }
public subscribe(subscriptions: FillsFeedSubscriptionParams) { public subscribe(subscriptions: FillsFeedSubscribeParams) {
if (this._connected) { if (this._connected) {
this._socket.send( this._socket.send(
JSON.stringify({ JSON.stringify({
@ -153,6 +156,19 @@ export class FillsFeed {
} }
} }
public unsubscribe(marketId: string) {
if (this._connected) {
this._socket.send(
JSON.stringify({
command: 'unsubscribe',
marketId,
}),
);
} else {
console.warn('[FillsFeed] attempt to unsubscribe when not connected');
}
}
public connected(): boolean { public connected(): boolean {
return this._connected; return this._connected;
} }