summaryrefslogtreecommitdiff
path: root/frontend/src/sagas/gameBrowser.js
blob: 7cd456678e9bd81d21a2914c5600473056ca8465 (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
56
57
58
59
60
61
62
63
64
65
// @flow
import { normalize } from 'normalizr';
import { push } from 'react-router-redux';
import type { SagaIterator } from 'redux-saga';
import { eventChannel } from 'redux-saga';
import { all, apply, call, put, take } from 'redux-saga/effects';
import type { SevenWondersSession } from '../api/sevenWondersApi';
import { actions as gameActions, types } from '../redux/games';
import { actions as playerActions } from '../redux/players';
import { game as gameSchema, gameList as gameListSchema } from '../schemas/games';

function* watchGames(session: SevenWondersSession): SagaIterator {
  const gamesChannel = yield eventChannel(session.watchGames());
  try {
    while (true) {
      const gameList = yield take(gamesChannel);
      const normGameList = normalize(gameList, gameListSchema);
      // for an empty game array, there is no players/games entity maps
      yield put(playerActions.updatePlayers(normGameList.entities.players || {}));
      yield put(gameActions.updateGames(normGameList.entities.games || {}));
    }
  } finally {
    yield apply(gamesChannel, gamesChannel.close);
  }
}

function* watchLobbyJoined(session: SevenWondersSession): SagaIterator {
  const joinedLobbyChannel = yield eventChannel(session.watchLobbyJoined());
  try {
    const joinedLobby = yield take(joinedLobbyChannel);
    const normalized = normalize(joinedLobby, gameSchema);
    const gameId = normalized.result;
    yield put(playerActions.updatePlayers(normalized.entities.players));
    yield put(gameActions.updateGames(normalized.entities.games));
    yield put(gameActions.enterLobby(normalized.entities.games[gameId]));
    yield put(push(`/lobby/${gameId}`));
  } finally {
    yield apply(joinedLobbyChannel, joinedLobbyChannel.close);
  }
}

function* createGame(session: SevenWondersSession): SagaIterator {
  while (true) {
    const { gameName } = yield take(types.REQUEST_CREATE_GAME);
    // $FlowFixMe
    yield apply(session, session.createGame, [gameName]);
  }
}

function* joinGame(session: SevenWondersSession): SagaIterator {
  while (true) {
    const { gameId } = yield take(types.REQUEST_JOIN_GAME);
    // $FlowFixMe
    yield apply(session, session.joinGame, [gameId]);
  }
}

export function* gameBrowserSaga(session: SevenWondersSession): SagaIterator {
  yield all([
    call(watchGames, session),
    call(watchLobbyJoined, session),
    call(createGame, session),
    call(joinGame, session),
  ]);
}
bgstack15