SHARE
TWEET

Untitled

a guest Jun 25th, 2019 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export const FIREBASE = Symbol('FIREBASE');
  2.  
  3. // Middleware constructor
  4. export default firebase => {
  5.   // Init auth providers
  6.   const providers = {
  7.     fb: new firebase.auth.FacebookAuthProvider(),
  8.     google: new firebase.auth.GoogleAuthProvider()
  9.   };
  10.  
  11.   // This is the basic middleware pattern
  12.   return ({ dispatch }) => next => action => {
  13.     const firebaseAction = action[FIREBASE];
  14.  
  15.     // Let the action pass if it is not a 'firebase' action
  16.     if (typeof firebaseAction === "undefined") {
  17.       return next(action);
  18.     }
  19.  
  20.     const { withFirebase, types, callBack } = firebaseAction;
  21.     const [request, success, failure] = types;
  22.  
  23.     const promise = withFirebase(firebase, providers);
  24.     dispatch({
  25.       type: request,
  26.       payload: {}
  27.     });
  28.  
  29.     // This is an async immediately invoked function
  30.     (async () => {
  31.       const [error, response] = await handle(promise);
  32.  
  33.       if (error) {
  34.         return dispatch({
  35.           type: failure,
  36.           payload: error
  37.         })
  38.       }
  39.  
  40.       if (response) {
  41.         dispatch({
  42.           type: success,
  43.           payload: response
  44.           });
  45.         callBack && callBack();
  46.       }
  47.     })();
  48.   };
  49. };
  50.  
  51. // More on this explained below
  52. function handle(promise) {
  53.   return promise.then(res => [null, res]).catch(err => [err, null]);
  54. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top