UNPKG

3.09 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = createGameActionMiddleware;
7/**
8 * So we have lots of actions that come to us from the nextActions queue in the reducer. Some of
9 * them can be dispatched as-is, but many of them require us to run an action creator function to
10 * e.g. decrypt or encrypt something as is appropriate. This middleware detects such actions and
11 * sees if we have a cooresponding action based on a simple naming convention.
12 *
13 * actions.SEED_RNG_DECRYPT => actions.seedRngDecryptAction
14 */
15
16function 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 * two kinds of actions are allowed - you can either be a human that did an action on your turn or you can be a computer handling the most recent action in nextactions
34 */
35 function checkActionAllowed(state, action) {
36 // non-game actions are always allowed
37 if (!actions[action.type]) {
38 return;
39 }
40 // also if we don't have a turn order yet, nbd
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 // no queue, check if it's an allowed action
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 // implement thunk
77 if (typeof action === "function") {
78 return action(dispatch, getState);
79 }
80 return next(action);
81 };
82 };
83 };
84}
85//# sourceMappingURL=game-action-middleware.js.map
\No newline at end of file