summaryrefslogtreecommitdiff
path: root/frontend/src/sagas/lobby.js
blob: 3f23a125cf318d443eda58fa763fc5fd38c02c14 (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
45
46
47
48
49
50
51
52
53
54
55
// @flow
import { normalize } from 'normalizr';
import { push } from 'react-router-redux';
import type { Channel } from 'redux-saga';
import { eventChannel } from 'redux-saga';
import { apply, call, put, take, all } from 'redux-saga/effects';
import { SevenWondersSession } from '../api/sevenWondersApi';
import { actions as gameActions, types } from '../redux/games';
import { actions as playerActions } from '../redux/players';
import { game as gameSchema } from '../schemas/games';

function getCurrentGameId(): number {
  const path = window.location.pathname;
  return path.split('lobby/')[1];
}

function* watchLobbyUpdates(session: SevenWondersSession): * {
  const currentGameId: number = getCurrentGameId();
  const lobbyUpdatesChannel: Channel = yield eventChannel(session.watchLobbyUpdated(currentGameId));
  try {
    while (true) {
      const lobby = yield take(lobbyUpdatesChannel);
      const normalized = normalize(lobby, gameSchema);
      yield put(gameActions.updateGames(normalized.entities.games));
      yield put(playerActions.updatePlayers(normalized.entities.players));
    }
  } finally {
    yield apply(lobbyUpdatesChannel, lobbyUpdatesChannel.close);
  }
}

function* watchGameStart(session: SevenWondersSession): * {
  const currentGameId = getCurrentGameId();
  const gameStartedChannel = yield eventChannel(session.watchGameStarted(currentGameId));
  try {
    yield take(gameStartedChannel);
    yield put(gameActions.enterGame());
    yield put(push('/game'));
  } finally {
    yield apply(gameStartedChannel, gameStartedChannel.close);
  }
}

function* startGame(session: SevenWondersSession): * {
  while (true) {
    yield take(types.REQUEST_START_GAME);
    yield apply(session, session.startGame, []);
  }
}

function* lobbySaga(session: SevenWondersSession): * {
  yield all([call(watchLobbyUpdates, session), call(watchGameStart, session), call(startGame, session)]);
}

export default lobbySaga;
bgstack15