import { DEFAULT_PREFIX , WEBSOCKET_BROKEN , WEBSOCKET_BEGIN_RECONNECT , WEBSOCKET_RECONNECT_ATTEMPT , WEBSOCKET_RECONNECTED , WEBSOCKET_CLOSED , WEBSOCKET_CONNECT , WEBSOCKET_DISCONNECT , WEBSOCKET_ERROR , WEBSOCKET_MESSAGE , WEBSOCKET_OPEN , WEBSOCKET_SEND , } from './actionTypes' ; import { Action , Deserializer } from './types' ; type WithProtocols = [ string [ ] ] | [ string [ ] , string ] ; type WithPrefix = [ string ] ; type ConnectRestArgs = [ ] | WithPrefix | WithProtocols ; type BuiltAction < T > = { type : string ; meta : { timestamp : Date ; } ; payload ? : T ; } ; private const isProtocols = ( args ) : args is WithProtocols => Array . isArray ( args [ 0 ] ) ; param { string } actionType param { T } payload returns { BuiltAction < T > } function buildAction < T > ( actionType , payload ? , meta ? ) { const base = { type : actionType , meta : { timestamp : new Date ( ) , ... meta , } , ... ( payload instanceof Error ? { error : true } : null ) , } ; return payload ? { ... base , payload } : base ; } export const connect = ( url , ... args ) => { let prefix ; let protocols ; if ( args . length === 1 ) { [ protocols , prefix ] = isProtocols ( args ) ? args : [ undefined , args [ 0 ] ] ; } if ( args . length === 2 ) { [ protocols , prefix ] = args ; } return buildAction ( `${ prefix || DEFAULT_PREFIX }::${ WEBSOCKET_CONNECT }` , { url , protocols , } ) ; } ; export const disconnect = ( prefix ? ) => buildAction ( `${ prefix || DEFAULT_PREFIX }::${ WEBSOCKET_DISCONNECT }` ) ; export const send = ( msg , prefix ? ) => buildAction ( `${ prefix || DEFAULT_PREFIX }::${ WEBSOCKET_SEND }` , msg ) ; export const beginReconnect = ( prefix ) => buildAction ( `${ prefix }::${ WEBSOCKET_BEGIN_RECONNECT }` ) ; export const reconnectAttempt = ( count , prefix ) => buildAction ( `${ prefix }::${ WEBSOCKET_RECONNECT_ATTEMPT }` , { count } ) ; export const reconnected = ( prefix ) => buildAction ( `${ prefix }::${ WEBSOCKET_RECONNECTED }` ) ; export const open = ( event , prefix ) => buildAction ( `${ prefix }::${ WEBSOCKET_OPEN }` , event ) ; export const broken = ( prefix ) => buildAction ( `${ prefix }::${ WEBSOCKET_BROKEN }` ) ; export const closed = ( event , prefix ) => buildAction ( `${ prefix }::${ WEBSOCKET_CLOSED }` , event ) ; export const message = ( event , prefix , deserializer ? ) => buildAction ( `${ prefix }::${ WEBSOCKET_MESSAGE }` , { event , message : deserializer ? deserializer ( event . data ) : event . data , origin : event . origin , } ) ; export const error = ( originalAction , err , prefix ) => buildAction ( `${ prefix }::${ WEBSOCKET_ERROR }` , err , { message : err . message , name : err . name , originalAction , } ) ;