Skip to content

Commit

Permalink
Merge pull request #337 from NIAEFEUP/feature/websockets
Browse files Browse the repository at this point in the history
Add WebSocket integration
  • Loading branch information
Process-ing authored Nov 10, 2024
2 parents dc4cdba + 020dbc8 commit 5edb800
Show file tree
Hide file tree
Showing 3 changed files with 157 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
70 changes: 70 additions & 0 deletions src/api/socket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { io, Socket } from "socket.io-client";
import backendApi from "./backend";

const SOCKET_URL = (import.meta.env.VITE_APP_PROD == 0 ? 'ws://' : 'wss://') + 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);
}

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

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 5edb800

Please sign in to comment.