import * as firebase from 'firebase/app' ; import { MiddlewareAPI , Action } from 'redux' ; import { RootState } from './reducer' ; const firestore = firebase . firestore ( ) . enablePersistence ( ) . then ( ( ) => firebase . firestore ( ) ) . catch ( ( err ) => { switch ( err . code ) { case 'failed-precondition' : case 'unimplemented' : default : return firebase . firestore ( ) ; } } ) ; const subscriptions = { } ; export type SubscribeFn = ( db : firebase . firestore . Firestore ) => Promise < firebase . firestore . DocumentSnapshot > ; export type SuccessFn = ( doc : firebase . firestore . DocumentSnapshot ) => Action ; export type FailureFn = ( err : Error ) => Action ; export default ( { dispatch , getState } ) => next => action => { const { type , name , subscribe , unsubscribe , started , success , failure , payload = { } } = action ; if ( ! subscribe && ! unsubscribe ) { return next ( action ) ; } if ( subscribe ) { dispatch ( started ) ; firestore . then ( db => { subscriptions [ name ] = subscribe ( db ) . then ( doc => dispatch ( success ( doc ) ) , err => dispatch ( failure ( err ) ) ) ; } ) ; return ; } if ( unsubscribe ) { subscriptions [ unsubscribe ] ( ) ; return ; } } ;