integration-websocket-rest-api
Version:
A JavaScript library for easy integration of REST API and WebSocket communication with state management in JS applications.
63 lines (51 loc) • 1.49 kB
JavaScript
const WebSocket = require("websocket").w3cwebsocket;
class WebSocketClient {
constructor(wsUrl) {
this.wsUrl = wsUrl;
this.socket = null;
this.receivedMessages = [];
this.receivedMessageCallback = null;
}
openConnection() {
this.socket = new WebSocket(this.wsUrl);
return new Promise((resolve, reject) => {
this.socket.onopen = () => {
console.log("WebSocket connection opened");
resolve();
};
this.socket.onmessage = (event) => {
const message = event.data;
this.receivedMessages.push(message);
// Handling recieved messages
if (this.receivedMessageCallback) {
this.receivedMessageCallback(message);
}
};
this.socket.onerror = (error) => {
console.error(`WebSocket error: ${error}`);
reject(error);
};
});
}
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;