2022-01-12 17:13:30 +00:00
|
|
|
import io from "socket.io-client";
|
|
|
|
|
|
|
|
let client = null;
|
|
|
|
|
|
|
|
class SocketIOHelper {
|
|
|
|
socketUrl = null;
|
|
|
|
|
|
|
|
constructor(url) {
|
|
|
|
if (!url) return;
|
|
|
|
|
|
|
|
this.socketUrl = url;
|
|
|
|
|
|
|
|
if (client) return;
|
|
|
|
|
2022-01-25 09:54:21 +00:00
|
|
|
const origin = window.location.origin;
|
|
|
|
|
|
|
|
client = io(origin, {
|
2022-01-12 17:13:30 +00:00
|
|
|
withCredentials: true,
|
|
|
|
transports: ["websocket", "polling"],
|
|
|
|
eio: 4,
|
2022-01-25 09:54:21 +00:00
|
|
|
path: url,
|
2022-01-12 17:13:30 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
client.on("connect", () => console.log("socket is connected"));
|
|
|
|
client.on("connect_error", (err) =>
|
|
|
|
console.log("socket connect error", err)
|
|
|
|
);
|
|
|
|
client.on("disconnect", () => console.log("socket is disconnected"));
|
|
|
|
}
|
|
|
|
|
|
|
|
get isEnabled() {
|
|
|
|
return this.socketUrl !== null;
|
|
|
|
}
|
|
|
|
|
|
|
|
emit = ({ command, data, room = null }) => {
|
|
|
|
if (!this.isEnabled) return;
|
|
|
|
|
|
|
|
if (!client.connected) {
|
|
|
|
client.on("connect", () => {
|
2022-02-25 16:08:02 +00:00
|
|
|
if (room !== null) {
|
|
|
|
client.to(room).emit(command, data);
|
|
|
|
} else {
|
|
|
|
client.emit(command, data);
|
|
|
|
}
|
2022-01-12 17:13:30 +00:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
room ? client.to(room).emit(command, data) : client.emit(command, data);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
on = (eventName, callback) => {
|
|
|
|
if (!this.isEnabled) return;
|
2022-02-25 16:08:02 +00:00
|
|
|
|
2022-01-12 17:13:30 +00:00
|
|
|
if (!client.connected) {
|
|
|
|
client.on("connect", () => {
|
|
|
|
client.on(eventName, callback);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
client.on(eventName, callback);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export default SocketIOHelper;
|