1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
import { call, put, take } from 'redux-saga/effects'
import { eventChannel } from 'redux-saga'
import { fromJS } from 'immutable'
import { push } from 'react-router-redux'
import { NEW_GAME, JOIN_GAME, CREATE_GAME } from './constants'
import { newGame, joinGame } from './actions'
function createSocketChannel(socket) {
return eventChannel(emit => {
const makeHandler = (type) => (event) => {
const response = fromJS(JSON.parse(event.body))
emit({
type,
response
})
}
const newGameHandler = makeHandler(NEW_GAME)
const joinGameHandler = makeHandler(JOIN_GAME)
const newGame = socket.subscribe('/topic/games', newGameHandler)
const joinGame = socket.subscribe('/user/queue/join-game', joinGameHandler)
const unsubscribe = () => {
newGame.unsubscribe()
joinGame.unsubscribe()
}
return unsubscribe
})
}
export function* watchGames(socketConnection) {
const { socket } = socketConnection
const socketChannel = createSocketChannel(socket)
while (true) {
const { type, response } = yield take(socketChannel)
switch (type) {
case NEW_GAME:
yield put(newGame(response))
break;
case JOIN_GAME:
yield put(joinGame(response))
break;
default:
console.error('Unknown type')
}
}
}
export function* createGame(socketConnection) {
const { name } = yield take(CREATE_GAME)
const { socket } = socketConnection
socket.send("/app/lobby/create-game", JSON.stringify({
'gameName': name,
'playerName': 'Cesar92'
}), {})
}
export function* gameBrowserSaga(socketConnection) {
yield put(push('/lobby'))
yield [
call(watchGames, socketConnection),
call(createGame, socketConnection)
]
}
export default gameBrowserSaga
|