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

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

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()
}

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