AllenYuan

auth - local storage middleware

Apr 24th, 2020
498
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import agent from './agent';
  2.  
  3. function isPromise(v) {
  4.   return v && typeof v.then === 'function';
  5. }
  6.  
  7. const promiseMiddleware = store => next => action => {
  8.   // if the action's payload is a promise, trigger this middleware
  9.   if (isPromise(action.payload)) {
  10.     // trigger UI's loading state
  11.     store.dispatch({ type: 'ASYNC_START', subtype: action.type });
  12.     // let promise succeed/fail
  13.     action.payload.then(
  14.       // if it succeeds, mutate payload into the promised data and
  15.       // dispatch action to store
  16.       res => {
  17.         action.payload = res;
  18.         store.dispatch(action);
  19.       },
  20.       // failure => set an error flag on action and mutate payload into
  21.       // the error message. dispatch action to store
  22.       error => {
  23.         action.error = true;
  24.         action.payload = error.response.body;
  25.         store.dispatch(action);
  26.       }
  27.     );
  28.  
  29.     return;
  30.   }
  31.  
  32.   // if the action payload is not a promise, send the action over to the next middleware
  33.   // or dispatch it to the store if this is the last middleware in the chain
  34.   next(action);
  35. }
  36.  
  37. const localStorageMiddleware = store => next => action => {
  38.   // set the token if we have it
  39.   if (action.type === 'REGISTER' || action.type === 'LOGIN') {
  40.     if (!action.error) {
  41.       window.localStorage.setItem('jwt', action.payload.user.token);
  42.       // pass the token to the HTTP client so we can use it to make calls where we need
  43.       // authentication.
  44.       agent.setToken(action.payload.user.token);
  45.     }
  46.   }
  47.   // if we're logging out, clear the authentication token from local storage and the http client
  48.   else if (action.type === 'LOGOUT') {
  49.     window.localStorage.setItem('jwt', '');
  50.     agent.setToken(null);
  51.   }
  52.   next(action);
  53. };
  54.  
  55. export {
  56.   localStorageMiddleware,
  57.   promiseMiddleware
  58. };
Advertisement
Add Comment
Please, Sign In to add comment