summaryrefslogtreecommitdiff
path: root/frontend/src/sagas/home.js
blob: 15f951629ea15b0866e81fe24c96249460f946eb (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
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