1 | "use strict";
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.default = createGameActionMiddleware;
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | function createGameActionMiddleware(actions) {
|
17 | var actionMap = {};
|
18 | Object.keys(actions).forEach(function (key) {
|
19 | var value = actions[key];
|
20 | if (typeof value !== "string" || key !== value) {
|
21 | return;
|
22 | }
|
23 | var camelCase = value.split("_").map(function (word) {
|
24 | return word[0].toUpperCase() + word.slice(1).toLowerCase();
|
25 | }).join("");
|
26 | var actionCreator = camelCase[0].toLowerCase() + camelCase.slice(1);
|
27 | if (actions[actionCreator]) {
|
28 | actionMap[value] = actions[actionCreator];
|
29 | }
|
30 | });
|
31 |
|
32 | |
33 |
|
34 |
|
35 | function checkActionAllowed(state, action) {
|
36 |
|
37 | if (!actions[action.type]) {
|
38 | return;
|
39 | }
|
40 |
|
41 | if (!state.game || !state.game.turn) {
|
42 | return;
|
43 | }
|
44 | var sender = action.agent || state.client.keys.id;
|
45 | if (state.game.nextActions.length > 0) {
|
46 | var queueUser = state.game.nextActions[0].playerId;
|
47 | if (sender !== queueUser) {
|
48 | throw new Error("queue wants user " + queueUser + " but user " + sender + " acted");
|
49 | }
|
50 | }
|
51 |
|
52 | else if (state.game.allowedActions[action.type] !== true) {
|
53 | throw new Error(sender + " attempted to do non-allowed action " + action.type);
|
54 | } else if (state.game.turn !== sender) {
|
55 | throw new Error(sender + " acted out of turn; it's " + state.game.turn + "'s turn");
|
56 | }
|
57 | }
|
58 |
|
59 | return function gameActionMiddleware(store) {
|
60 | return function (next) {
|
61 | return function (action) {
|
62 | var state = store.getState();
|
63 | var dispatch = store.dispatch,
|
64 | getState = store.getState;
|
65 |
|
66 | checkActionAllowed(state, action);
|
67 | if (!state.client.loadingState && actionMap[action.type] && action._fromQueue && !action._dispatchedFromQueue) {
|
68 | action = actionMap[action.type](action);
|
69 | dispatch = function dispatch(action) {
|
70 | return store.dispatch(Object.assign({}, action, {
|
71 | _fromQueue: true,
|
72 | _dispatchedFromQueue: true
|
73 | }));
|
74 | };
|
75 | }
|
76 |
|
77 | if (typeof action === "function") {
|
78 | return action(dispatch, getState);
|
79 | }
|
80 | return next(action);
|
81 | };
|
82 | };
|
83 | };
|
84 | }
|
85 |
|
\ | No newline at end of file |