summaryrefslogtreecommitdiff
path: root/frontend/src/containers/HomePage/saga.js
blob: 0fbe8a45d73cf5ff43cf6a7a918d9cf431bfaed5 (plain)
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
import { call, put, take } from 'redux-saga/effects'
import { eventChannel } from 'redux-saga'
import { ENTER_GAME } from './actions'
import { setUsername } from '../UserRepo/actions'

import gameBrowserSaga from '../GameBrowser/saga'

function* sendUsername(socketConnection) {
  const { username: playerName } = yield take(ENTER_GAME)
  const { socket } = socketConnection

  socket.send("/app/chooseName", JSON.stringify({
    playerName
  }), {})
}

function createSocketChannel(socket) {
  return eventChannel(emit => {
    const receiveUsername = socket.subscribe('/user/queue/nameChoice', event => {
      emit(JSON.parse(event.body))
    })

    const unsubscribe = () => {
      receiveUsername.unsubscribe()
    }

    return unsubscribe
  })
}

function* validateUsername(socketConnection) {
  const { socket } = socketConnection
  const socketChannel = createSocketChannel(socket)

  const response = yield take(socketChannel)

  if (response.error) {
    return false
  }

  yield put(setUsername(response.userName, response.displayName, response.index))
  yield call(gameBrowserSaga, socketConnection)
  return true
}

function* homeSaga(socketConnection) {
  let validated = false
  do {
    const [, usernameValid] = yield [
      call(sendUsername, socketConnection),
      call(validateUsername, socketConnection)
    ]
    validated = usernameValid
  } while (!validated)
}

export default homeSaga
bgstack15