refactor server side socket for connection with new Game service

This commit is contained in:
Sorrel Bri 2020-05-02 23:22:57 -07:00
parent b8eb3770d9
commit a02576532d

View file

@ -5,41 +5,43 @@ const io = socketIO({ cookie: false });
const gameQueries = require('./data/queries/game'); const gameQueries = require('./data/queries/game');
const gameServices = require('./services/gameServices'); const gameServices = require('./services/gameServices');
io.on('connection', socket=> { io.on('connection', async socket=> {
socket.emit('connected', {message: 'socket connected'}); socket.emit('connected', {message: 'socket connected'});
socket.on('connect_room', data => { socket.on('connect_room', async data => {
if (data.user && data.user.email) { if (data.user && data.user.email) {
delete data.user.email; delete data.user.email;
} }
const room= data.room; const room = data.room;
const roomIo = io.of(room); const roomIo = io.of(room);
roomIo.on('connection', socket => { roomIo.on('connection', async socket => {
socket.emit('connected') socket.emit('connected')
socket.emit('new_user', data); socket.emit('new_user', data);
socket.on('connect_game', data => { socket.on('connect_game', data => {
const game = `game-${data.game.id}`; const game = `game-${data.game.id}`;
socket.join(game, async () => { socket.join(game, async () => {
// ! temp // ! temp
gameServices.initGame({id: data.game.id}) await gameServices.initGame({id: data.game.id})
// ! end-temp // ! end-temp
const gameData = await gameServices.getBoard(data.game.id); const gameData = await gameServices.getDataForUI(data.game.id);
io.of(room).to(game).emit('game_connected', gameData) io.of(room).to(game).emit('game_connected', gameData)
}); });
}); });
socket.on('make_move', data => { socket.on('make_move', async data => {
const { user, move, board, game, room } = data; const { user, move, board, game, room } = data;
const gameNsp = `game-${data.game.id}`; const gameNsp = `game-${data.game.id}`;
try { try {
const updatedBoard = gameServices.makeMove(1, move); const result = await gameServices.makeMove({ id: 1, move });
console.log(result)
let socketAction = 'update_board';
if (result.message) socketAction = 'error';
socket.join(gameNsp, () => { socket.join(gameNsp, () => {
io.of(room).to(gameNsp).emit('update_board', updatedBoard) io.of(room).to(gameNsp).emit(socketAction, result)
}); });
} }
catch (err) { catch (e) {
socket.join(gameNsp, () => { socket.join(gameNsp, () => {
io.of(room).to(gameNsp).emit('error', err) io.of(room).to(gameNsp).emit('error', e)
}); });
} }