summaryrefslogtreecommitdiff
path: root/frontend/src/sagas/usernameChoice.js
blob: da720e9f57af79285a6e9773aec82b43b1a0bdbc (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
import { call, take, put } from 'redux-saga/effects'
import { eventChannel } from 'redux-saga'
import { push } from 'react-router-redux'
import { fromJS } from 'immutable'

import { actions, types } from '../redux/players'

function usernameValidationChannel(socket) {
  return eventChannel(emitter => {
    const receiveUsernameHandler = socket.subscribe('/user/queue/nameChoice', event => {
      emitter(fromJS(JSON.parse(event.body)))
    })
    return () => receiveUsernameHandler.unsubscribe()
  })
}

function *usernameValidation({ socket }) {
  const usernameChannel = yield call(usernameValidationChannel, socket)
  const user = yield take(usernameChannel)
  yield put(actions.setUsername(user.get('username'), user.get('displayName'), user.get('index')))
  usernameChannel.close()
  yield put(push('/games'))
}

function *sendUsername({ socket }) {
  const { username } = yield take(types.CHOOSE_USERNAME)

  yield socket.send('/app/chooseName', JSON.stringify({
    playerName: username
  }))
}

function *usernameChoiceSaga(wsConnection) {
  // TODO: Run sendUsername in loop when we have the ability to cancel saga on route change
  yield [
    call(sendUsername, wsConnection),
    call(usernameValidation, wsConnection),
  ]
}

export default usernameChoiceSaga
bgstack15