116 lines
2.5 KiB
JavaScript
116 lines
2.5 KiB
JavaScript
import { io } from 'socket.io-client';
|
|
|
|
const WS_URL = import.meta.env.VITE_WS_URL || 'http://localhost:3000';
|
|
|
|
class SocketService {
|
|
constructor() {
|
|
this.socket = null;
|
|
this.listeners = new Map();
|
|
}
|
|
|
|
connect() {
|
|
if (this.socket?.connected) {
|
|
return this.socket;
|
|
}
|
|
|
|
this.socket = io(WS_URL, {
|
|
withCredentials: true,
|
|
transports: ['websocket', 'polling'],
|
|
});
|
|
|
|
this.socket.on('connect', () => {
|
|
console.log('WebSocket connected:', this.socket.id);
|
|
});
|
|
|
|
this.socket.on('disconnect', () => {
|
|
console.log('WebSocket disconnected');
|
|
});
|
|
|
|
this.socket.on('error', (error) => {
|
|
console.error('WebSocket error:', error);
|
|
});
|
|
|
|
return this.socket;
|
|
}
|
|
|
|
disconnect() {
|
|
if (this.socket) {
|
|
this.socket.disconnect();
|
|
this.socket = null;
|
|
}
|
|
}
|
|
|
|
on(event, callback) {
|
|
if (!this.socket) {
|
|
this.connect();
|
|
}
|
|
this.socket.on(event, callback);
|
|
|
|
if (!this.listeners.has(event)) {
|
|
this.listeners.set(event, []);
|
|
}
|
|
this.listeners.get(event).push(callback);
|
|
}
|
|
|
|
off(event, callback) {
|
|
if (this.socket) {
|
|
this.socket.off(event, callback);
|
|
}
|
|
|
|
if (this.listeners.has(event)) {
|
|
const callbacks = this.listeners.get(event);
|
|
const index = callbacks.indexOf(callback);
|
|
if (index > -1) {
|
|
callbacks.splice(index, 1);
|
|
}
|
|
}
|
|
}
|
|
|
|
emit(event, data) {
|
|
if (!this.socket) {
|
|
this.connect();
|
|
}
|
|
this.socket.emit(event, data);
|
|
}
|
|
|
|
// Game-specific methods
|
|
joinRoom(roomCode, userId) {
|
|
this.emit('joinRoom', { roomCode, userId });
|
|
}
|
|
|
|
startGame(roomId, roomCode, userId) {
|
|
this.emit('startGame', { roomId, roomCode, userId });
|
|
}
|
|
|
|
revealAnswer(roomCode, roomId, userId, answerIndex) {
|
|
this.emit('revealAnswer', { roomCode, roomId, userId, answerIndex });
|
|
}
|
|
|
|
updateScore(participantId, score, roomCode, roomId, userId) {
|
|
this.emit('updateScore', { participantId, score, roomCode, roomId, userId });
|
|
}
|
|
|
|
nextQuestion(roomCode, roomId, userId) {
|
|
this.emit('nextQuestion', { roomCode, roomId, userId });
|
|
}
|
|
|
|
endGame(roomId, roomCode, userId) {
|
|
this.emit('endGame', { roomId, roomCode, userId });
|
|
}
|
|
|
|
updateRoomPack(roomId, roomCode, userId, questions) {
|
|
this.emit('updateRoomPack', { roomId, roomCode, userId, questions });
|
|
}
|
|
|
|
importQuestions(roomId, roomCode, userId, sourcePackId, questionIndices) {
|
|
this.emit('importQuestions', {
|
|
roomId,
|
|
roomCode,
|
|
userId,
|
|
sourcePackId,
|
|
questionIndices,
|
|
});
|
|
}
|
|
}
|
|
|
|
export default new SocketService();
|