From 0b78c78a0af8060cf3354b24e502b37dda77ef73 Mon Sep 17 00:00:00 2001 From: Sorrel Bri Date: Sat, 25 Jan 2020 16:50:18 -0800 Subject: [PATCH] refacor sockets on server and client to utilize dispatch for socket meessages --- packages/play-node-go/play-node-go/src/App.js | 21 ++---- packages/play-node-go/play-node-go/src/io.js | 30 ++++++++ .../play-node-go/src/pages/Room/Room.js | 41 ++-------- .../src/reducers/init/stateReducer.init.js | 4 +- .../reducers/socket/stateReducer.socket.js | 30 ++++++++ .../play-node-go/src/reducers/stateReducer.js | 7 +- .../server/controllers/api/apiGame.js | 5 +- .../server/controllers/api/apiRoom.js | 5 +- packages/play-node-go/server/socket.js | 75 +++++-------------- 9 files changed, 106 insertions(+), 112 deletions(-) create mode 100644 packages/play-node-go/play-node-go/src/io.js create mode 100644 packages/play-node-go/play-node-go/src/reducers/socket/stateReducer.socket.js diff --git a/packages/play-node-go/play-node-go/src/App.js b/packages/play-node-go/play-node-go/src/App.js index bf8fad1..05cb505 100644 --- a/packages/play-node-go/play-node-go/src/App.js +++ b/packages/play-node-go/play-node-go/src/App.js @@ -1,5 +1,4 @@ import React, {useState, useEffect, useReducer} from 'react'; -import socketIOClient from 'socket.io-client'; import config from './config'; import { Switch, Route, BrowserRouter as Router, Redirect } from 'react-router-dom'; import MainWrapper from './pages/Layout/MainWrapper/MainWrapper'; @@ -8,14 +7,11 @@ import { initState } from './reducers/init/stateReducer.init'; import indexServices from './services/api/indexServices'; import './App.scss'; -export const socket = socketIOClient(config.socketAddress); +import socketIOClient from 'socket.io-client'; +const socket = socketIOClient(config.socketAddress); function App() { - const [fetchData, setFetchData] = useState(); - const [socketData, setSocketData] = useState(); - const [error, setError] = useState([]); - const [ state, dispatch ] = useReducer( stateReducer, {}, @@ -39,11 +35,8 @@ function App() { }, []) const socketConnect = () => { - socket.removeAllListeners(); - socket.emit('connect'); - socket.on('connected', data => setSocketData('socket connected')); - socket.on('connect_error', err => setError([...error, err])); - socket.on('error', err => setError([...error, err])) + if (state.connect) return; + dispatch({type:'SOCKET', message: 'LAUNCH', body:{socket, dispatch}}); } useEffect(() => { @@ -53,7 +46,7 @@ function App() { return ( -
+
@@ -84,9 +77,7 @@ function App() {

React Boilerplate

- {fetchData ?

{fetchData}

: <>} - {socketData ?

{socketData}

: <>} - {/* {error ? error.map(err =>

{err}

): <>} */} +

{state.connect ? '✓' : ' ⃠'}

); diff --git a/packages/play-node-go/play-node-go/src/io.js b/packages/play-node-go/play-node-go/src/io.js new file mode 100644 index 0000000..4219a30 --- /dev/null +++ b/packages/play-node-go/play-node-go/src/io.js @@ -0,0 +1,30 @@ +import socketIOClient from 'socket.io-client'; +import config from './config'; + + +const launch = (socket, dispatch) => { + + socket.on('connected', () => { + dispatch({type:'SOCKET', message:'CONNECTED', body:{}}); + }); + socket.on('connect_error', err => { + dispatch({type: 'ERR', message:'SOCKET_ERROR', body: {socketError: err}}); + }); + socket.on('error', err => { + dispatch({type: 'ERR', message:'SOCKET_ERROR', body: {socketError: err}}); + }); + + socket.on('room_connected', (data) => { + dispatch({type: 'ROOM', message: 'CONNECT_ROOM', body: data}); + }); + + socket.on('new_user', (data) => { + console.log(data) + }) + + return socket; +} + +export { + launch +} \ No newline at end of file diff --git a/packages/play-node-go/play-node-go/src/pages/Room/Room.js b/packages/play-node-go/play-node-go/src/pages/Room/Room.js index 7c7b885..fb9d938 100644 --- a/packages/play-node-go/play-node-go/src/pages/Room/Room.js +++ b/packages/play-node-go/play-node-go/src/pages/Room/Room.js @@ -11,10 +11,9 @@ import ActionError from '../../components/Error/ActionError/ActionError'; import Development from '../../components/Display/Development/Development'; const Room = (props) => { - const state = props.state; - const dispatch = props.dispatch; + const { state, dispatch} = props; const roomId = parseInt(useParams().id) || 0; - const [ socket, setSocket ] = useState(false); + const socket = socketIOClient(`${config.socketAddress}/${roomId}`); const fetchRoomAPI = async () => { const response = await roomsServices.getRoomService(roomId); @@ -33,44 +32,20 @@ const Room = (props) => { }, []) // ! [start] roomSocket - const roomSocket = socketIOClient(`${config.socketAddress}/${roomId}`) const roomSocketConnect = () => { - roomSocket.emit('connect'); - // ! dispatch data - roomSocket.on('connect', socket => { - setSocket(true) - }); - roomSocket.on('join_game_request', data => { - // ! - console.log(data) - }) - roomSocket.on('connect_error', err => { - setSocket(false) - // ! - console.log(err); - }); - roomSocket.on('error', err => { - setSocket(false) - // ! - console.log(err); - }); + const action = { + type: 'SOCKET', + message: 'CONNECT_ROOM', + body: {user: state.user, room: roomId, socket} + } + dispatch(action) } useEffect(() => { roomSocketConnect(); }, []) - useEffect(() => { - const data = { - user: state.user, - game: state.joinGame - }; - console.log('emitting request') - console.log(data) - roomSocket.emit('join_game_request', data) - }, [state.joinGame]) - // ! [end] const renderGames = () => { diff --git a/packages/play-node-go/play-node-go/src/reducers/init/stateReducer.init.js b/packages/play-node-go/play-node-go/src/reducers/init/stateReducer.init.js index 60d3e01..10a1ecc 100644 --- a/packages/play-node-go/play-node-go/src/reducers/init/stateReducer.init.js +++ b/packages/play-node-go/play-node-go/src/reducers/init/stateReducer.init.js @@ -1,6 +1,7 @@ //@ flow import type { state } from '../stateReducer'; +const socket = require('../../io'); export const initState = (): state => { return { @@ -9,6 +10,7 @@ export const initState = (): state => { currentRoom: {}, messages: {}, games: {}, - joinGame: {} + joinGame: {}, + socket: {} }; } \ No newline at end of file diff --git a/packages/play-node-go/play-node-go/src/reducers/socket/stateReducer.socket.js b/packages/play-node-go/play-node-go/src/reducers/socket/stateReducer.socket.js new file mode 100644 index 0000000..f7c12d8 --- /dev/null +++ b/packages/play-node-go/play-node-go/src/reducers/socket/stateReducer.socket.js @@ -0,0 +1,30 @@ +// @flow +import type { state, action } from '../stateReducer'; +import { stateReducer } from '../stateReducer'; +const io = require('../../io'); + +export const socketReducer = (state: state, action: action):state => { + switch(action.message) { + + case 'CONNECTED': + return {...state, connect: 'home'} + + case 'LAUNCH': { + const {socket, dispatch} = action.body; + const launchedSocket = io.launch(socket, dispatch); + return {...state, socket: launchedSocket}; + } + + case 'CONNECT_ROOM': { + const {socket, ...data} = action.body; + // if (Object.entries(state.socket)) { + // state.socket.close(); + // } + socket.emit('connect_room', data); + return {...state, socket, connect:''}; + } + + default: + return state; + } +} \ No newline at end of file diff --git a/packages/play-node-go/play-node-go/src/reducers/stateReducer.js b/packages/play-node-go/play-node-go/src/reducers/stateReducer.js index e642161..44c3425 100644 --- a/packages/play-node-go/play-node-go/src/reducers/stateReducer.js +++ b/packages/play-node-go/play-node-go/src/reducers/stateReducer.js @@ -6,11 +6,13 @@ import { indexReducer } from './index/stateReducer.index'; import { roomsReducer } from './rooms/stateReducer.rooms'; import { messagesReducer } from './messages/stateReducer.messages'; import { gamesReducer } from './games/stateReducer.games'; +import { socketReducer } from './socket/stateReducer.socket'; export type state = { user: {}, errors: {}, - messages: [] + messages: [], + state: {} } export type action = { @@ -40,6 +42,9 @@ export const stateReducer = (state: state, action: action): state => { case 'ROOMS': return roomsReducer(errorStrippedState, action); + case 'SOCKET': + return socketReducer(errorStrippedState, action); + case 'ERR': return errorReducer(errorStrippedState, action); diff --git a/packages/play-node-go/server/controllers/api/apiGame.js b/packages/play-node-go/server/controllers/api/apiGame.js index 48b8b16..df56844 100644 --- a/packages/play-node-go/server/controllers/api/apiGame.js +++ b/packages/play-node-go/server/controllers/api/apiGame.js @@ -2,15 +2,14 @@ const roomQueries = require('../../data/queries/room'); const messageQueries = require('../../data/queries/message'); const gameQueries = require('../../data/queries/game'); const moveQueries = require('../../data/queries/move'); -const { enableGameSocket } = require('../../socket'); const show = async (req, res, next) => { try { const gameId = req.params.id; if (!gameId) throw('missing game parameter') - const game = await gameQueries.findGameById(gameId); - enableGameSocket(game.room); + // TODO Promise.all() + const game = await gameQueries.findGameById(gameId); const record = await moveQueries.findGameRecord(gameId); res.status(200).json({game, record}) } diff --git a/packages/play-node-go/server/controllers/api/apiRoom.js b/packages/play-node-go/server/controllers/api/apiRoom.js index 7a108e4..e319484 100644 --- a/packages/play-node-go/server/controllers/api/apiRoom.js +++ b/packages/play-node-go/server/controllers/api/apiRoom.js @@ -1,7 +1,7 @@ const roomQueries = require('../../data/queries/room'); const messageQueries = require('../../data/queries/message'); const gameQueries = require('../../data/queries/game'); -const {enableRoomSocket} = require('../../socket'); +const socket = require('../../socket'); const getAll = async (req, res, next) => { try { @@ -21,7 +21,7 @@ const show = async (req, res, next) => { if (!roomId) throw('missing room parameter') // TODO eventually add check for user's private rooms - enableRoomSocket(roomId); + socket.roomSocket(roomId); const currentRoom = await roomQueries.findRoomById(roomId); const messages = await messageQueries.findMessageByRoom(roomId); @@ -30,6 +30,7 @@ const show = async (req, res, next) => { res.status(200).json(body); } catch (err) { + console.log(err) res.status(500).json(err); } } diff --git a/packages/play-node-go/server/socket.js b/packages/play-node-go/server/socket.js index e932e52..4df6a09 100644 --- a/packages/play-node-go/server/socket.js +++ b/packages/play-node-go/server/socket.js @@ -4,68 +4,29 @@ const io = socketIO({ cookie: false }); const gameQueries = require('./data/queries/game'); -io.on('connection', ()=> { - io.emit('connected', {message: 'socket connected'}); +io.on('connection', socket=> { + socket.emit('connected', {message: 'socket connected'}); + + socket.on('connect_room', data => { + const { user, room } = data; + const roomIo = io.of(room); + roomIo.emit('new_user', user) + // roomIo.on('connection', roomSocket => { + // }) + }); }) -const enableRoomSocket = () => { - const roomSocket = io.of(roomId); - roomSocket.on('connection', (socket) => { - - //! Join Game Request queries db for game, ensures unique player joining - socket.on('join_game_request', async data => { - const gameRequest = await logJoinGameRequest(data); - - if (gameRequest.err) { - roomSocket.emit('join_game_request_error', gameRequest.err); - } - - roomSocket.emit('join_game_request', gameRequest); - }); - - }); - return roomSocket; -} - -const enableGameSocket = (roomId) => { - const gameSocket = io.of(roomId); - let game; - gameSocket.on('connection', (socket) => { - socket.on('joined game', (gameId) => { - game = `game-${gameId}`; - console.log(gameId) - socket.join(game); - // socket - // .to(game) - io.sockets.in(game).emit('success', game) +const roomSocket = (roomId) => { + const roomIo = io.of(roomId) + roomIo.on('connection', socket => { + console.log('connected') + socket.on('connect_room', data => { + console.log(data) }) - - }); - // console.log(game) - // gameSocket - // .to(game) - // .emit(`success`, game) - // socket.on('hey', () => console.log('hey')) - - - return gameSocket; + }) } module.exports = { io, - enableRoomSocket, - enableGameSocket + roomSocket } - -async function logJoinGameRequest (data) { - const {user, game} = data; - const requestedGame = await gameQueries.findGameById(game.id); - - if (requestedGame.user_black === user.id) { - return { err: 'players must be unique' } - } - - const requestingUser = {...user}; - delete requestingUser.email; - return { requestingUser, requestedGame } -} \ No newline at end of file