summaryrefslogtreecommitdiff
path: root/sw-ui/src/sagas/gameBrowser.ts
blob: 868ec471455aaf2f6029e622cd830bfa19db5993 (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
import { push } from 'react-router-redux';
import { eventChannel, SagaIterator } from 'redux-saga';
import { all, apply, call, put, take } from 'redux-saga/effects';
import { ApiLobby } from '../api/model';
import { SevenWondersSession } from '../api/sevenWondersApi';
import { actions as gameActions, REQUEST_CREATE_GAME, REQUEST_JOIN_GAME } from '../redux/actions/lobby';

function* watchGames(session: SevenWondersSession): any {
  const gamesChannel = yield eventChannel(session.watchGames());
  try {
    while (true) {
      const gameList = yield take(gamesChannel);
      yield put(gameActions.updateGames(gameList));
    }
  } finally {
    yield apply(gamesChannel, gamesChannel.close);
  }
}

function* watchLobbyJoined(session: SevenWondersSession): any {
  const joinedLobbyChannel = yield eventChannel(session.watchLobbyJoined());
  try {
    const joinedLobby: ApiLobby = yield take(joinedLobbyChannel);
    yield put(gameActions.updateGames([joinedLobby]));
    yield put(gameActions.enterLobby(joinedLobby.id));
    yield put(push(`/lobby/${joinedLobby.id}`));
  } finally {
    yield apply(joinedLobbyChannel, joinedLobbyChannel.close);
  }
}

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

function* joinGame(session: SevenWondersSession): SagaIterator {
  while (true) {
    const { gameId } = yield take(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