Skip to content

Commit

Permalink
Add WebSocket integration
Browse files Browse the repository at this point in the history
  • Loading branch information
Process-ing committed Nov 9, 2024
1 parent dc4cdba commit 2032e24
Show file tree
Hide file tree
Showing 3 changed files with 160 additions and 0 deletions.
86 changes: 86 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"react-router-dom": "^6.3.0",
"react-sortablejs": "^6.1.4",
"react-toastify": "^9.1.1",
"socket.io-client": "^4.8.0",
"sortablejs": "^1.15.2",
"swr": "^2.2.5",
"tailwind-merge": "^2.2.0",
Expand Down
73 changes: 73 additions & 0 deletions src/api/socket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { io, Socket } from "socket.io-client";
import backendApi from "./backend";

const SOCKET_URL = 'ws://' + backendApi.BACKEND_URL.split('//')[1];

class OptionalSocket {
private socket: Socket | null;

constructor() {
this.socket = null;
}

set(socket: Socket) {
this.socket = socket;
}

unset() {
this.socket = null;
}

use<T>(callback: (socket: Socket) => T): T {
if (!this.socket) {
throw new Error('Socket is not connected');
}
return callback(this.socket);
}
}

class SessionsSocket {
private url: string;
private socket: OptionalSocket;

constructor(url: string) {
this.url = url;
this.socket = new OptionalSocket();
}

connect() {
const newSocket = io(this.url, {
auth: {
token: 'dummy', // TODO: Replace with actual federated authentication token
}
});
this.socket.set(newSocket);
console.log('Connected to socket');
}

disconnect() {
this.socket.use(socket => socket.disconnect());
this.socket.unset();

console.log('Disconnected from socket');
}

on(event: string, callback: (...args: any[]) => void) {
this.socket.use(socket => socket.on(event, callback));
}

off(event: string, callback?: (...args: any[]) => void) {
this.socket.use(socket => socket.off(event, callback));
}

emit(event: string, ...args: any[]) {
this.socket.use(socket => socket.emit(event, args));
}
}

const sessionsSocket = new SessionsSocket(SOCKET_URL);

export {
sessionsSocket,
SOCKET_URL,
};

0 comments on commit 2032e24

Please sign in to comment.