remove singleton for websocket

This commit is contained in:
AnisHADJARAB 2024-11-06 16:07:31 +00:00
parent 41b3ba552f
commit 4957f724d3
2 changed files with 33 additions and 48 deletions

View File

@ -2,7 +2,7 @@
import { INotification } from '~/models/notification.model';
import { IProcess } from '~/models/process.model';
// import Database from './database';
import { WebSocketClient } from '../websockets';
import { initWebsocket, sendMessage } from '../websockets';
import { ApiReturn, Member } from '../../dist/pkg/sdk_client';
import ModalService from './modal.service';
import { navigate } from '../router';
@ -19,7 +19,6 @@ export default class Services {
private static instance: Services;
private current_process: string | null = null;
private sdkClient: any;
private websocketConnection: WebSocketClient | null = null;
private processes: IProcess[] | null = null;
private notifications: INotification[] | null = null;
private subscriptions: { element: Element; event: string; eventHandler: string }[] = [];
@ -58,11 +57,8 @@ export default class Services {
public async addWebsocketConnection(url: string): Promise<void> {
// const services = await Services.getInstance();
if (!this.websocketConnection) {
console.log('Opening new websocket connection');
const newClient = new WebSocketClient(url, this);
this.websocketConnection = newClient;
}
const newClient = initWebsocket(url);
}
public isPaired(): boolean | undefined {
@ -131,28 +127,25 @@ export default class Services {
}
async sendNewTxMessage(message: string) {
if (!this.websocketConnection) {
throw new Error('No websocket connection');
}
// console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ newTxMessage:", message)
await this.websocketConnection.sendMessage('NewTx', message);
await sendMessage('NewTx', message);
}
async sendCommitMessage(message: string) {
// console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ CommitMessage:", message)
await this.websocketConnection?.sendMessage('Commit', message);
await sendMessage('Commit', message);
}
async sendCipherMessages(ciphers: string[]) {
for (let i = 0; i < ciphers.length; i++) {
const cipher = ciphers[i];
await this.websocketConnection?.sendMessage('Cipher', cipher);
await sendMessage('Cipher', cipher);
}
}
async sendFaucetMessage(message: string): Promise<void> {
// console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ faucetMessage:", message)
await this.websocketConnection?.sendMessage('Faucet', message);
await sendMessage('Faucet', message);
}
async parseCipher(message: string) {
// try {
@ -281,7 +274,7 @@ export default class Services {
let tx = await this.sdkClient.response_prd(outpointCommitment, prdString, true);
console.log('🚀 ~ Services ~ pairDevice ~ tx:', tx);
if (tx.ciphers_to_send) {
tx.ciphers_to_send.forEach((cipher: string) => this.websocketConnection?.sendMessage('Cipher', cipher));
tx.ciphers_to_send.forEach((cipher: string) => sendMessage('Cipher', cipher));
}
navigate('process');
}

View File

@ -1,19 +1,15 @@
import { AnkFlag, CachedMessage } from 'dist/pkg/sdk_client';
import { AnkFlag } from 'dist/pkg/sdk_client';
import Services from './services/service';
// import { AnkFlag, AnkNetworkMsg, CachedMessage } from "../dist/pkg/sdk_client";
class WebSocketClient {
private ws: WebSocket;
private messageQueue: string[] = [];
let ws: WebSocket;
let messageQueue: string[] = [];
let services: Services
export async function initWebsocket(url: string) {
ws = new WebSocket(url);
services = await Services.getInstance()
constructor(
url: string,
private services: Services,
) {
this.ws = new WebSocket(url);
if (this.ws !== null) {
this.ws.onopen = async (event) => {
if (ws !== null) {
ws.onopen = async (event) => {
console.log('WebSocket connection established');
const amount = await services.getAmount();
@ -22,16 +18,16 @@ class WebSocketClient {
const faucetMsg = await services.createFaucetMessage();
await services.sendFaucetMessage(faucetMsg);
}
while (this.messageQueue.length > 0) {
const message = this.messageQueue.shift();
while (messageQueue.length > 0) {
const message = messageQueue.shift();
if (message) {
this.ws.send(message);
ws.send(message);
}
}
};
// Listen for messages
this.ws.onmessage = (event) => {
ws.onmessage = (event) => {
const msgData = event.data;
// console.log("Received text message: ", msgData);
@ -41,7 +37,6 @@ class WebSocketClient {
const feeRate = 0.0001;
const parsedMessage = JSON.parse(msgData);
// console.log("🚀 ~ WebSocketClient ~ parsedMessage:", parsedMessage)
const services = await Services.getInstance();
switch (parsedMessage.flag) {
case 'NewTx':
await services.parseNewTx(parsedMessage.content);
@ -89,20 +84,20 @@ class WebSocketClient {
};
// Listen for possible errors
this.ws.onerror = (event) => {
ws.onerror = (event) => {
console.error('WebSocket error:', event);
};
// Listen for when the connection is closed
this.ws.onclose = (event) => {
ws.onclose = (event) => {
console.log('WebSocket is closed now.');
};
}
}
// Method to send messages
public async sendMessage(flag: AnkFlag, message: string): Promise<void> {
if (this.ws.readyState === WebSocket.OPEN) {
export async function sendMessage(flag: AnkFlag, message: string): Promise<void> {
if (ws.readyState === WebSocket.OPEN) {
const networkMessage = {
flag: flag,
content: message,
@ -112,26 +107,23 @@ class WebSocketClient {
// services.parseCipher(JSON.stringify(networkMessage))
// }
console.log('Sending message:', JSON.stringify(networkMessage));
this.ws.send(JSON.stringify(networkMessage));
ws.send(JSON.stringify(networkMessage));
} else {
console.error('WebSocket is not open. ReadyState:', this.ws.readyState);
this.messageQueue.push(message);
console.error('WebSocket is not open. ReadyState:', ws.readyState);
messageQueue.push(message);
}
}
public getUrl(): string {
return this.ws.url;
export function getUrl(): string {
return ws.url;
}
public sendNormalMessage(message: string) {
this.ws.send(message);
export function sendNormalMessage(message: string) {
ws.send(message);
console.log('Sending message:', JSON.stringify(message));
}
// Method to close the WebSocket connection
public close(): void {
this.ws.close();
export function close(): void {
ws.close();
}
}
export { WebSocketClient };