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 { INotification } from '~/models/notification.model';
import { IProcess } from '~/models/process.model'; import { IProcess } from '~/models/process.model';
// import Database from './database'; // import Database from './database';
import { WebSocketClient } from '../websockets'; import { initWebsocket, sendMessage } from '../websockets';
import { ApiReturn, Member } from '../../dist/pkg/sdk_client'; import { ApiReturn, Member } from '../../dist/pkg/sdk_client';
import ModalService from './modal.service'; import ModalService from './modal.service';
import { navigate } from '../router'; import { navigate } from '../router';
@ -19,7 +19,6 @@ export default class Services {
private static instance: Services; private static instance: Services;
private current_process: string | null = null; private current_process: string | null = null;
private sdkClient: any; private sdkClient: any;
private websocketConnection: WebSocketClient | null = null;
private processes: IProcess[] | null = null; private processes: IProcess[] | null = null;
private notifications: INotification[] | null = null; private notifications: INotification[] | null = null;
private subscriptions: { element: Element; event: string; eventHandler: string }[] = []; private subscriptions: { element: Element; event: string; eventHandler: string }[] = [];
@ -58,11 +57,8 @@ export default class Services {
public async addWebsocketConnection(url: string): Promise<void> { public async addWebsocketConnection(url: string): Promise<void> {
// const services = await Services.getInstance(); // const services = await Services.getInstance();
if (!this.websocketConnection) {
console.log('Opening new websocket connection'); console.log('Opening new websocket connection');
const newClient = new WebSocketClient(url, this); const newClient = initWebsocket(url);
this.websocketConnection = newClient;
}
} }
public isPaired(): boolean | undefined { public isPaired(): boolean | undefined {
@ -131,28 +127,25 @@ export default class Services {
} }
async sendNewTxMessage(message: string) { async sendNewTxMessage(message: string) {
if (!this.websocketConnection) {
throw new Error('No websocket connection');
}
// console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ newTxMessage:", message) // console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ newTxMessage:", message)
await this.websocketConnection.sendMessage('NewTx', message); await sendMessage('NewTx', message);
} }
async sendCommitMessage(message: string) { async sendCommitMessage(message: string) {
// console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ CommitMessage:", message) // console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ CommitMessage:", message)
await this.websocketConnection?.sendMessage('Commit', message); await sendMessage('Commit', message);
} }
async sendCipherMessages(ciphers: string[]) { async sendCipherMessages(ciphers: string[]) {
for (let i = 0; i < ciphers.length; i++) { for (let i = 0; i < ciphers.length; i++) {
const cipher = ciphers[i]; const cipher = ciphers[i];
await this.websocketConnection?.sendMessage('Cipher', cipher); await sendMessage('Cipher', cipher);
} }
} }
async sendFaucetMessage(message: string): Promise<void> { async sendFaucetMessage(message: string): Promise<void> {
// console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ faucetMessage:", message) // console.log("🚀 ~ WebSocketClient ~ this.ws.onopen= ~ faucetMessage:", message)
await this.websocketConnection?.sendMessage('Faucet', message); await sendMessage('Faucet', message);
} }
async parseCipher(message: string) { async parseCipher(message: string) {
// try { // try {
@ -281,7 +274,7 @@ export default class Services {
let tx = await this.sdkClient.response_prd(outpointCommitment, prdString, true); let tx = await this.sdkClient.response_prd(outpointCommitment, prdString, true);
console.log('🚀 ~ Services ~ pairDevice ~ tx:', tx); console.log('🚀 ~ Services ~ pairDevice ~ tx:', tx);
if (tx.ciphers_to_send) { 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'); 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 Services from './services/service';
// import { AnkFlag, AnkNetworkMsg, CachedMessage } from "../dist/pkg/sdk_client";
class WebSocketClient { let ws: WebSocket;
private ws: WebSocket; let messageQueue: string[] = [];
private messageQueue: string[] = []; let services: Services
export async function initWebsocket(url: string) {
ws = new WebSocket(url);
services = await Services.getInstance()
constructor( if (ws !== null) {
url: string, ws.onopen = async (event) => {
private services: Services,
) {
this.ws = new WebSocket(url);
if (this.ws !== null) {
this.ws.onopen = async (event) => {
console.log('WebSocket connection established'); console.log('WebSocket connection established');
const amount = await services.getAmount(); const amount = await services.getAmount();
@ -22,16 +18,16 @@ class WebSocketClient {
const faucetMsg = await services.createFaucetMessage(); const faucetMsg = await services.createFaucetMessage();
await services.sendFaucetMessage(faucetMsg); await services.sendFaucetMessage(faucetMsg);
} }
while (this.messageQueue.length > 0) { while (messageQueue.length > 0) {
const message = this.messageQueue.shift(); const message = messageQueue.shift();
if (message) { if (message) {
this.ws.send(message); ws.send(message);
} }
} }
}; };
// Listen for messages // Listen for messages
this.ws.onmessage = (event) => { ws.onmessage = (event) => {
const msgData = event.data; const msgData = event.data;
// console.log("Received text message: ", msgData); // console.log("Received text message: ", msgData);
@ -41,7 +37,6 @@ class WebSocketClient {
const feeRate = 0.0001; const feeRate = 0.0001;
const parsedMessage = JSON.parse(msgData); const parsedMessage = JSON.parse(msgData);
// console.log("🚀 ~ WebSocketClient ~ parsedMessage:", parsedMessage) // console.log("🚀 ~ WebSocketClient ~ parsedMessage:", parsedMessage)
const services = await Services.getInstance();
switch (parsedMessage.flag) { switch (parsedMessage.flag) {
case 'NewTx': case 'NewTx':
await services.parseNewTx(parsedMessage.content); await services.parseNewTx(parsedMessage.content);
@ -89,20 +84,20 @@ class WebSocketClient {
}; };
// Listen for possible errors // Listen for possible errors
this.ws.onerror = (event) => { ws.onerror = (event) => {
console.error('WebSocket error:', event); console.error('WebSocket error:', event);
}; };
// Listen for when the connection is closed // Listen for when the connection is closed
this.ws.onclose = (event) => { ws.onclose = (event) => {
console.log('WebSocket is closed now.'); console.log('WebSocket is closed now.');
}; };
} }
} }
// Method to send messages // Method to send messages
public async sendMessage(flag: AnkFlag, message: string): Promise<void> { export async function sendMessage(flag: AnkFlag, message: string): Promise<void> {
if (this.ws.readyState === WebSocket.OPEN) { if (ws.readyState === WebSocket.OPEN) {
const networkMessage = { const networkMessage = {
flag: flag, flag: flag,
content: message, content: message,
@ -112,26 +107,23 @@ class WebSocketClient {
// services.parseCipher(JSON.stringify(networkMessage)) // services.parseCipher(JSON.stringify(networkMessage))
// } // }
console.log('Sending message:', JSON.stringify(networkMessage)); console.log('Sending message:', JSON.stringify(networkMessage));
this.ws.send(JSON.stringify(networkMessage)); ws.send(JSON.stringify(networkMessage));
} else { } else {
console.error('WebSocket is not open. ReadyState:', this.ws.readyState); console.error('WebSocket is not open. ReadyState:', ws.readyState);
this.messageQueue.push(message); messageQueue.push(message);
} }
} }
public getUrl(): string { export function getUrl(): string {
return this.ws.url; return ws.url;
} }
public sendNormalMessage(message: string) { export function sendNormalMessage(message: string) {
this.ws.send(message); ws.send(message);
console.log('Sending message:', JSON.stringify(message)); console.log('Sending message:', JSON.stringify(message));
} }
// Method to close the WebSocket connection // Method to close the WebSocket connection
public close(): void { export function close(): void {
this.ws.close(); ws.close();
} }
}
export { WebSocketClient };