redux#MiddlewareAPI TypeScript Examples
The following examples show how to use
redux#MiddlewareAPI.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: createInterceptorMiddleware.ts From diagram-maker with Apache License 2.0 | 6 votes |
export function createInterceptorMiddleware<NodeType, EdgeType>(
actionInterceptor?: ActionInterceptor<NodeType, EdgeType>,
) {
return (store: MiddlewareAPI) => (next: Dispatch<Action>) => (action: Action) => {
if (!actionInterceptor) {
next(action);
return;
}
actionInterceptor(action, next, store.getState);
};
}
Example #2
Source File: application.ts From grafana-chinese with Apache License 2.0 | 6 votes |
toggleLogActionsMiddleware: Middleware<{}, StoreState> = (store: MiddlewareAPI<Dispatch, StoreState>) => (
next: Dispatch
) => (action: AnyAction) => {
const isLogActionsAction = action.type === toggleLogActions.type;
if (isLogActionsAction) {
return next(action);
}
const logActionsTrue =
window && window.location && window.location.search && window.location.search.indexOf('logActions=true') !== -1;
const logActionsFalse =
window && window.location && window.location.search && window.location.search.indexOf('logActions=false') !== -1;
const logActions = store.getState().application.logActions;
if (logActionsTrue && !logActions) {
store.dispatch(toggleLogActions());
}
if (logActionsFalse && logActions) {
store.dispatch(toggleLogActions());
}
return next(action);
}
Example #3
Source File: firebaseMiddleware.ts From bad-cards-game with GNU Affero General Public License v3.0 | 4 votes |
export default function firebaseMiddleware(firebase: Firebase) {
const middleware = function middleware(params: MiddlewareAPI<Dispatch, GameState>) {
const { dispatch /*getState*/ } = params;
let newPlayersSubscription: Subscription | null = null;
let newRoundSubscription: Subscription | null = null;
firebase.auth.onAuthStateChanged((user) => {
if (user) {
firebase.uid = user.uid;
ReactGA.set({ userId: user.uid });
user.getIdToken(true).then((idToken) => {
Axios.defaults.headers.common['Authorization'] = `Bearer ${idToken}`;
});
setTimeout(() => {
dispatch(userLoaded(true, user.uid, user.displayName || ''));
}, 1000);
} else {
dispatch(userLoaded(false, '', ''));
}
});
const checkDisplayName = (displayName: string) => {
if (!displayName.trim()) {
dispatch(error('Display name not valid', 'Profile error', ErrorType.PROFILE));
return false;
}
return true;
};
return function (next: Dispatch) {
return async function (action: GameActionTypes) {
switch (action.type) {
case LOGIN:
firebase.doSignInWithEmailAndPassword(action.payload.email, action.payload.password).catch((e) => {
dispatch(error(e.message, 'Login error', ErrorType.LOGIN));
});
break;
case LOGIN_AS_GUEST:
if (checkDisplayName(action.payload.displayName)) {
firebase
.doSignInAsGuest()
.then(() => {
dispatch(newDisplayName(action.payload.displayName));
})
.catch((e) => {
dispatch(error(e.message, 'Login error', ErrorType.LOGIN));
});
}
break;
case SIGNUP:
if (checkDisplayName(action.payload.displayName)) {
firebase
.doCreateUserWithEmailAndPassword(action.payload.email, action.payload.password)
.then(() => {
dispatch(newDisplayName(action.payload.displayName));
})
.catch((e) => {
dispatch(error(e.message, 'Signup error', ErrorType.SIGNUP));
});
}
break;
case NEW_DISPLAY_NAME:
if (checkDisplayName(action.payload.displayName)) {
firebase.changeDisplayName(action.payload.displayName);
} else {
return;
}
break;
case DELETE_USER:
firebase.deleteUser()?.catch((e) => {
dispatch(error(e.message, 'Delete user', ErrorType.DELETE_USER));
});
break;
case GAME_HOSTING:
(async () => {
const response = await Axios.get<{ roomID: string }>(`/game/createRoom/${action.payload.lang}`);
dispatch(joinGame(response.data.roomID));
})();
break;
case GAME_JOINING_EXISTING:
Axios.get<{ roomID?: string; error?: string }>('/game/joinExisting')
.then((response) => {
if (response.data.roomID) {
dispatch(joinGame(response.data.roomID));
} else {
dispatch(error(response.data.error || 'No room available now', 'Join game', ErrorType.JOIN));
}
})
.catch((e) => {
dispatch(error(e.message, 'Join game', ErrorType.JOIN));
});
break;
case GAME_JOINED:
(async () => {
try {
await firebase.enterRoom(action.payload.roomID);
// Richiedo il pack della room corrente
const packRef = await firebase.getPackRef();
// Mi assicuro che sia scaricato il pack prima di iniziare il gioco
const pack = (await Axios.get<Pack>(`/game/pack/${packRef.lang}/${packRef.selectedPack}`)).data;
// Attendo l'inizio del gioco
firebase.notifyOnGameStart().then(() => {
dispatch(gameStarted(pack));
});
newRoundSubscription = firebase.notifyNewRound$(pack).subscribe((newRoundData) => {
const { round, cards, role, blackCard, judgeID } = newRoundData;
dispatch(newRound(round, cards, role, blackCard, judgeID));
});
newPlayersSubscription = firebase.notifyNewPlayers$(pack).subscribe((players) => {
dispatch(updatePlayers(players));
});
} catch (e) {
dispatch(error('Cannot join the game', 'Join game', ErrorType.JOIN));
}
})();
break;
case GAME_START:
await firebase.startGame();
break;
case GAME_EXITED:
newRoundSubscription?.unsubscribe();
newPlayersSubscription?.unsubscribe();
await firebase.exitRoom();
break;
case GAME_SEND_SELECTED:
firebase.sendSelected(action.payload.cards);
break;
case GAME_SEND_WINNER:
await Axios.post('/game/sendWinner', {
player: action.payload.player.uid,
roomID: firebase.roomID,
});
break;
}
return next(action);
};
};
};
return middleware;
}
Example #4
Source File: reduxTester.ts From grafana-chinese with Apache License 2.0 | 4 votes |
reduxTester = <State>(args?: ReduxTesterArguments<State>): ReduxTesterGiven<State> => {
const dispatchedActions: AnyAction[] = [];
const logActionsMiddleWare: Middleware<{}, Partial<StoreState>> = (
store: MiddlewareAPI<Dispatch, Partial<StoreState>>
) => (next: Dispatch) => (action: AnyAction) => {
// filter out thunk actions
if (action && typeof action !== 'function') {
dispatchedActions.push(action);
}
return next(action);
};
const preloadedState = args?.preloadedState ?? (({} as unknown) as State);
const debug = args?.debug ?? false;
let store: EnhancedStore<State> | null = null;
const givenRootReducer = (rootReducer: Reducer<State>): ReduxTesterWhen<State> => {
store = configureStore<State>({
reducer: rootReducer,
middleware: [logActionsMiddleWare, thunk],
preloadedState,
});
setStore(store as any);
return instance;
};
const whenActionIsDispatched = (
action: any,
clearPreviousActions?: boolean
): ReduxTesterWhen<State> & ReduxTesterThen<State> => {
if (clearPreviousActions) {
dispatchedActions.length = 0;
}
store.dispatch(action);
return instance;
};
const whenAsyncActionIsDispatched = async (
action: any,
clearPreviousActions?: boolean
): Promise<ReduxTesterWhen<State> & ReduxTesterThen<State>> => {
if (clearPreviousActions) {
dispatchedActions.length = 0;
}
await store.dispatch(action);
return instance;
};
const thenDispatchedActionShouldEqual = (...actions: AnyAction[]): ReduxTesterWhen<State> => {
if (debug) {
console.log('Dispatched Actions', JSON.stringify(dispatchedActions, null, 2));
}
if (!actions.length) {
throw new Error('thenDispatchedActionShouldEqual has to be called with at least one action');
}
expect(dispatchedActions).toEqual(actions);
return instance;
};
const thenDispatchedActionPredicateShouldEqual = (
predicate: (dispatchedActions: AnyAction[]) => boolean
): ReduxTesterWhen<State> => {
if (debug) {
console.log('Dispatched Actions', JSON.stringify(dispatchedActions, null, 2));
}
expect(predicate(dispatchedActions)).toBe(true);
return instance;
};
const instance = {
givenRootReducer,
whenActionIsDispatched,
whenAsyncActionIsDispatched,
thenDispatchedActionShouldEqual,
thenDispatchedActionPredicateShouldEqual,
};
return instance;
}