Skip to content

Instantly share code, notes, and snippets.

@andreasasprou
Created June 10, 2017 15:51
Show Gist options
  • Save andreasasprou/d23ef72de932311149347423ec034f7d to your computer and use it in GitHub Desktop.
Save andreasasprou/d23ef72de932311149347423ec034f7d to your computer and use it in GitHub Desktop.
/* 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