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

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

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

    const unsubscribe = () => receiveUsernameHandler.unsubscribe()

    return unsubscribe
  })
}

function *usernameValidation({ socket }) {
  const usernameChannel = usernameValidationChannel(socket)

  const user = yield take(usernameChannel)
  yield put(actions.setUsername(user.username, user.displayName, user.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