Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import LoginActions from '../LoginRedux'
- import {startsWith} from 'lodash'
- let buffer = []
- const authMiddleware = store => next => action => {
- const state = store.getState()
- let isTokenExpired = false
- // On sort le plus tôt possible
- if (action.type === 'REFRESH_TOKEN_REQUEST') {
- return next(action)
- }
- // Lors du succès du refresh on dispatch toutes les actions
- // stockées dans le buffer
- if (action.type === 'REFRESH_TOKEN_SUCCESS') {
- next(action)
- if (buffer.length > 0) {
- buffer.forEach(action => store.dispatch(action))
- buffer = []
- }
- }
- // pour toute autre action ne commençant pas par REFRESH_TOKEN
- if (!startsWith(action.type, 'REFRESH_TOKEN')) {
- // si on est sur le bon écran
- if (state && isValidScreen()) {
- isTokenExpired = isExpired(state.login.token)
- // si le token est expiré
- if (state.login.token && isTokenExpired) {
- // si le token n'est pas en cours de refresh
- // et si le buffer est bien vide
- if (!state.login.refreshingToken && buffer.length <= 0) {
- store.dispatch(LoginActions.refreshTokenRequest(state.login.refreshToken))
- }
- // sinon on sauvegarde l'action pour la "dispatcher" plus tard
- buffer.push(action)
- }
- }
- }
- // on retourne l'action au prochain reducer
- if (!isTokenExpired && action.type !== 'REFRESH_TOKEN_SUCCESS') {
- return next(action)
- }
- }
- export default authMiddleware
Add Comment
Please, Sign In to add comment