summaryrefslogtreecommitdiff
path: root/frontend/src/sagas/home.js
blob: 579c7fd699390f38fe4235d60adb7326bfd4982c (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
import { apply, call, put, take } from 'redux-saga/effects';
import { createSubscriptionChannel } from '../utils/websocket';
import { push } from 'react-router-redux';

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

function* sendUsername({ socket }) {
  while (true) {
    const { username } = yield take(types.REQUEST_CHOOSE_USERNAME);
    yield apply(socket, socket.send, ['/app/chooseName', JSON.stringify({ playerName: username })]);
  }
}

function* validateUsername({ socket }) {
  const usernameChannel = yield call(createSubscriptionChannel, socket, '/user/queue/nameChoice');
  while (true) {
    const user = yield take(usernameChannel);
    yield put(actions.setCurrentPlayer(user));
    yield apply(usernameChannel, usernameChannel.close);
    yield put(push('/games'));
  }
}

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

export default usernameChoiceSaga;
bgstack15