import * as ioClient from 'socket.io-client' ; import { all , fork , take , call , put , cancel } from 'redux-saga/effects' ; import { actionIds } from '../common' ; import { eventChannel } from 'redux-saga' ; import { currencyUpdateReceivedAction } from '../actions' ; function connect ( ) { const socket = ioClient . connect ( 'http://localhost:1337/' , null ) ; return new Promise ( ( resolve , reject ) => { socket . on ( 'connect' , ( ) => { socket . emit ( 'messages' ) ; resolve ( { socket } ) ; } ) ; socket . on ( 'connect_error' , err => { console . log ( 'connect failed :-(' ) ; reject ( new Error ( 'ws:connect_failed ' ) ) ; } ) ; } ) . catch ( error => ( { socket , error } ) ) ; } function subscribe ( socket ) { return eventChannel ( emit => { socket . on ( 'currency' , message => { console . log ( message ) ; emit ( currencyUpdateReceivedAction ( message ) ) ; } ) ; socket . on ( 'disconnect' , e => { } ) ; socket . on ( 'error' , error => { console . log ( 'Error while trying to connect, TODO: proper handle of this event' ) ; } ) ; return ( ) => { } ; } ) ; } function * read ( socket ) { const channel = yield call ( subscribe , socket ) ; while ( true ) { let action = yield take ( channel ) ; yield put ( action ) ; } } function * flow ( ) { while ( true ) { yield take ( actionIds . START_SOCKET_SUBSCRIPTION ) ; const { socket , error } = yield call ( connect ) ; if ( socket ) { console . log ( 'connection to socket succeeded' ) ; const ioTask = yield fork ( handleIO , socket ) ; yield take ( actionIds . STOP_SOCKET_SUBSCRIPTION ) ; yield cancel ( ioTask ) ; socket . disconnect ( ) ; } else { console . log ( 'error connecting' ) ; } } } function * handleIO ( socket ) { yield fork ( read , socket ) ; } export function * socketRootSaga ( ) { yield all ( [ fork ( flow ) ] ) ; }