node-go/packages/server/socket.js

62 lines
2 KiB
JavaScript
Raw Normal View History

// TODO const someSocketLogic = require('./middleware/socketssockets/...');
2020-05-30 23:01:13 +00:00
const socketIO = require("socket.io");
const io = socketIO({ cookie: false });
2020-05-12 01:18:42 +00:00
// const gameQueries = require('./data/queries/game');
2020-05-30 23:01:13 +00:00
const moveQueries = require("./data/queries/move");
const gameServices = require("./services/gameServices")(moveQueries);
2020-05-30 23:01:13 +00:00
io.on("connection", async (socket) => {
socket.emit("connected", { message: "socket connected" });
socket.on("connect_room", async (data) => {
if (data.user && data.user.email) {
delete data.user.email;
}
const room = data.room;
2020-01-30 01:01:46 +00:00
const roomIo = io.of(room);
2020-05-30 23:01:13 +00:00
roomIo.on("connection", async (socket) => {
socket.emit("connected");
socket.emit("new_user", data);
socket.on("connect_game", (data) => {
2020-01-30 01:01:46 +00:00
const game = `game-${data.game.id}`;
socket.join(game, async () => {
2020-05-12 01:18:42 +00:00
const gameRecord = await moveQueries.findGameRecord(data.game.id);
2020-05-30 23:01:13 +00:00
console.log("gameRecord from db");
console.log(gameRecord);
await gameServices.initGame({ id: data.game.id, gameRecord });
const { board, ...meta } = await gameServices.getDataForUI(
data.game.id
);
io.of(room).to(game).emit("game_connected", { board, meta });
2020-01-30 01:01:46 +00:00
});
});
2020-05-30 23:01:13 +00:00
socket.on("make_move", async (data) => {
const { user, move, board, game, room } = data;
2020-02-01 06:22:43 +00:00
const gameNsp = `game-${data.game.id}`;
2020-05-30 23:01:13 +00:00
2020-02-01 06:22:43 +00:00
try {
2020-05-30 23:01:13 +00:00
const { board, message, ...meta } = await gameServices.makeMove({
id: data.game.id,
2020-05-30 23:01:13 +00:00
move,
});
const socketAction = message ? "error" : "update_board";
2020-02-01 06:22:43 +00:00
socket.join(gameNsp, () => {
2020-05-30 23:01:13 +00:00
io.of(room)
.to(gameNsp)
.emit(socketAction, { board, meta, message });
2020-02-01 06:22:43 +00:00
});
2020-05-30 23:01:13 +00:00
} catch (e) {
console.log(e);
2020-02-01 06:22:43 +00:00
socket.join(gameNsp, () => {
2020-05-30 23:01:13 +00:00
io.of(room).to(gameNsp).emit("error", e);
2020-02-01 06:22:43 +00:00
});
}
2020-05-30 23:01:13 +00:00
});
2020-01-30 01:01:46 +00:00
});
2020-05-30 23:01:13 +00:00
});
});
module.exports = {
2020-05-30 23:01:13 +00:00
io,
};