2024-03-29 20:08:34 -04:00
|
|
|
// WebSocketService.tsx
|
|
|
|
|
import { io, Socket } from 'socket.io-client';
|
|
|
|
|
|
2024-09-26 00:34:30 -04:00
|
|
|
// Must (manually) sync these types to server/socket/socket.js
|
|
|
|
|
|
|
|
|
|
export type AnswerSubmissionToBackendType = {
|
|
|
|
|
roomName: string;
|
|
|
|
|
username: string;
|
|
|
|
|
answer: string | number | boolean;
|
|
|
|
|
idQuestion: number;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export type AnswerReceptionFromBackendType = {
|
|
|
|
|
idUser: string;
|
|
|
|
|
username: string;
|
|
|
|
|
answer: string | number | boolean;
|
|
|
|
|
idQuestion: number;
|
|
|
|
|
};
|
|
|
|
|
|
2024-03-29 20:08:34 -04:00
|
|
|
class WebSocketService {
|
|
|
|
|
private socket: Socket | null = null;
|
|
|
|
|
|
|
|
|
|
connect(backendUrl: string): Socket {
|
2024-09-15 21:56:48 -04:00
|
|
|
// console.log(backendUrl);
|
2024-03-29 20:08:34 -04:00
|
|
|
this.socket = io(`${backendUrl}`, {
|
|
|
|
|
transports: ['websocket'],
|
|
|
|
|
reconnectionAttempts: 1
|
|
|
|
|
});
|
|
|
|
|
return this.socket;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
disconnect() {
|
|
|
|
|
if (this.socket) {
|
|
|
|
|
this.socket.disconnect();
|
|
|
|
|
this.socket = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
createRoom() {
|
|
|
|
|
if (this.socket) {
|
|
|
|
|
this.socket.emit('create-room');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
nextQuestion(roomName: string, question: unknown) {
|
|
|
|
|
if (this.socket) {
|
|
|
|
|
this.socket.emit('next-question', { roomName, question });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
launchStudentModeQuiz(roomName: string, questions: unknown) {
|
|
|
|
|
if (this.socket) {
|
|
|
|
|
this.socket.emit('launch-student-mode', { roomName, questions });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
endQuiz(roomName: string) {
|
|
|
|
|
if (this.socket) {
|
|
|
|
|
this.socket.emit('end-quiz', { roomName });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
joinRoom(enteredRoomName: string, username: string) {
|
|
|
|
|
if (this.socket) {
|
|
|
|
|
this.socket.emit('join-room', { enteredRoomName, username });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-26 00:34:30 -04:00
|
|
|
submitAnswer(answerData: AnswerSubmissionToBackendType
|
|
|
|
|
// roomName: string,
|
|
|
|
|
// answer: string | number | boolean,
|
|
|
|
|
// username: string,
|
|
|
|
|
// idQuestion: string
|
2024-03-29 20:08:34 -04:00
|
|
|
) {
|
|
|
|
|
if (this.socket) {
|
2024-09-26 00:34:30 -04:00
|
|
|
this.socket?.emit('submit-answer',
|
|
|
|
|
// {
|
|
|
|
|
// answer: answer,
|
|
|
|
|
// roomName: roomName,
|
|
|
|
|
// username: username,
|
|
|
|
|
// idQuestion: idQuestion
|
|
|
|
|
// }
|
|
|
|
|
answerData
|
|
|
|
|
);
|
2024-03-29 20:08:34 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const webSocketService = new WebSocketService();
|
|
|
|
|
export default webSocketService;
|