integration-websocket-rest-api
Version:
A JavaScript library for easy integration of REST API and WebSocket communication with state management in JS applications.
103 lines (87 loc) • 2.49 kB
JavaScript
const WebSocket = require("websocket").w3cwebsocket;
class WebSocketClient {
constructor(wsUrl) {
this.wsUrl = wsUrl;
this.socket = null;
this.receivedMessages = [];
this.receivedMessageCallback = null;
this.maxRetries = 3;
this.retryDelay = 1000;
this.isReconnecting = false;
}
openConnection() {
return this.connect();
}
connect() {
this.socket = new WebSocket(this.wsUrl);
return new Promise((resolve, reject) => {
this.socket.onopen = () => {
console.log("WebSocket connection opened");
if (this.isReconnecting) {
console.log("Reconnected successfully");
this.isReconnecting = false;
}
resolve();
};
this.socket.onmessage = (event) => {
const message = event.data;
this.receivedMessages.push(message);
// Handling received messages
if (this.receivedMessageCallback) {
this.receivedMessageCallback(message);
}
};
this.socket.onerror = (error) => {
console.error(`WebSocket error: ${error}`);
reject(error);
};
this.socket.onclose = () => {
console.log("WebSocket connection closed");
if (!this.isReconnecting) {
this.reconnect();
}
};
});
}
reconnect() {
if (this.maxRetries > 0) {
console.log(
`Attempting to reconnect. Remaining retries: ${this.maxRetries}`
);
this.isReconnecting = true;
this.maxRetries--;
setTimeout(() => {
this.connect()
.then(() => {
this.maxRetries = 3; // Reset retries on successful reconnection
})
.catch(() => {
this.reconnect();
});
}, this.retryDelay);
} else {
console.error("Max retries reached. Unable to reconnect.");
}
}
sendMessage(message) {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(message);
} else {
console.error("WebSocket connection is not open.");
}
}
// Set the callback function to handle received messages
getMessage(callback) {
this.receivedMessageCallback = callback;
}
getReceivedMessages() {
return this.receivedMessages;
}
closeConnection() {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.close();
console.log("WebSocket connection closed");
}
}
}
module.exports = WebSocketClient;