import { Middleware , MiddlewareAPI } from 'redux' ; import { Action , Options } from './types' ; import { error } from './actions' ; import * as actionTypes from './actionTypes' ; import ReduxWebSocket from './ReduxWebSocket' ; private const defaultOptions = { dateSerializer : null , prefix : actionTypes . DEFAULT_PREFIX , reconnectInterval : 2000 , reconnectOnClose : false , reconnectOnError : true , serializer : JSON . stringify , } ; param { Options } rawOptions returns { Middleware } export default ( rawOptions ? ) : Middleware => { const options = { ... defaultOptions , ... rawOptions } ; const { prefix , dateSerializer } = options ; const actionPrefixExp = RegExp ( `^${ prefix }::` ) ; const reduxWebsocket = new ReduxWebSocket ( options ) ; const handlers = { [ actionTypes . WEBSOCKET_CONNECT ] : reduxWebsocket . connect , [ actionTypes . WEBSOCKET_DISCONNECT ] : reduxWebsocket . disconnect , [ actionTypes . WEBSOCKET_SEND ] : reduxWebsocket . send , } ; return ( store ) => ( next ) => ( action ) => { const { dispatch } = store ; const { type : actionType } = action ; if ( actionType && actionType . match ( actionPrefixExp ) ) { const baseActionType = action . type . replace ( actionPrefixExp , '' ) ; const handler = Reflect . get ( handlers , baseActionType ) ; if ( action . meta && action . meta . timestamp && dateSerializer ) { action . meta . timestamp = dateSerializer ( action . meta . timestamp ) ; } if ( handler ) { try { handler ( store , action ) ; } catch ( err ) { dispatch ( error ( action , err , prefix ) ) ; } } } return next ( action ) ; } ; } ;