Created
June 10, 2017 15:51
-
-
Save andreasasprou/d23ef72de932311149347423ec034f7d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Connecting to a channel */ | |
export function connectToChannelListener() { | |
takeLatest(OPEN_CHANNEL, connectToChannelHandler); | |
} | |
export function* connectToChannelHandler({ uuid }) { | |
try { | |
const socket = yield call(connect, uuid); | |
const task = yield fork(handleIO, socket); | |
yield take(CLOSE_CHANNEL); // blocks until channel is closed | |
yield cancel(task); | |
} catch (error) { | |
// Deal with error | |
} | |
} | |
export function* handleIO(socket) { | |
yield fork(read, socket); | |
yield fork(write, socket); | |
} | |
function* read(socket) { | |
const channel = yield call(subscribe, socket); | |
while (true) { | |
let action = yield take(channel); | |
yield put(action); | |
} | |
} | |
function* write(socket) { | |
while (true) { | |
const { message } = yield take(SEND_MESSAGE); | |
socket.emit('message', message); | |
} | |
} | |
function connect(uuid) { | |
return new Promise(resolve => { | |
io(`api/${uuid}`) | |
.on('connection', socketioJwt.authorize({ | |
secret: 'your secret or public key', | |
timeout: 15000 // 15 seconds to send the authentication message | |
})).on('authenticated', (socket) => { | |
resolve(socket); | |
}).on('unauthorized', (error) => { | |
reject(error); | |
}); | |
}); | |
} | |
function subscribe(socket) { | |
return eventChannel(emit => { | |
socket.on('messages.new', ({ message }) => { | |
emit(receiveMessage(message)); | |
}); | |
socket.on('disconnect', (event) => { | |
// TODO: handle | |
}); | |
return () => {}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment