Skip to content

Commit

Permalink
using event emitter
Browse files Browse the repository at this point in the history
  • Loading branch information
pragmaxim committed Nov 22, 2024
1 parent 28a1821 commit ff964e0
Showing 1 changed file with 16 additions and 19 deletions.
35 changes: 16 additions & 19 deletions packages/web3/src/ws/websocket-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,51 +17,49 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.
*/

import WebSocket from 'ws';
import EventEmitter from 'eventemitter3';

type WsMessageType = string;
type WsSubscription = [WsMessageType, (params: any) => void];
export type WsMessageType = string;
export type WsSubscription = [WsMessageType, (params: any) => void];

export class WebSocketClient {
export class WebSocketClient extends EventEmitter {
private ws: WebSocket;
private subscriptions: WsSubscription[] = [];

constructor(endpoint: string, eventSubscriptions: WsSubscription[] = []) {
super();
this.ws = new WebSocket(endpoint);
eventSubscriptions.forEach(([messageType, callback]) => {
this.subscriptions.push([messageType, callback]);
});

this.ws.on('open', () => {
console.log('WebSocket connection opened');
this.subscribeToEvents();
this.emit('open');
this.subscribeToEvents(eventSubscriptions);
});

this.ws.on('message', (data) => {
try {
const parsedData = JSON.parse(data.toString());
this.subscriptions.forEach(([method, callback]) => {
if (parsedData.method === method) {
callback(parsedData.params);
}
});
this.emit(parsedData.method, parsedData.params);
} catch (error) {
console.error('Error parsing message:', error);
}
});

this.ws.on('error', (error) => {
console.error('WebSocket error:', error);
this.emit('error', error);
});

this.ws.on('close', () => {
console.log('WebSocket connection closed');
this.emit('close');
});
}

private subscribeToEvents() {
this.subscriptions.forEach(([method]) => {
console.log(`Subscribing to ${method}`);
this.ws.send(`subscribe:${method}`);
private subscribeToEvents(eventSubscriptions: WsSubscription[]) {
eventSubscriptions.forEach(([messageType, callback]) => {
this.on(messageType, callback);
console.log(`Subscribing to ${messageType}`);
this.ws.send(`subscribe:${messageType}`);
});
}

Expand All @@ -72,5 +70,4 @@ export class WebSocketClient {
close() {
this.ws.close();
}
}

}

0 comments on commit ff964e0

Please sign in to comment.