Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
// Sample ActionCable ES6 client
//
// To be used like:
//
// const myEventHandlerFunction = (event) => {
// console.log(event.message);
// }
//
// ActionCableClient.connect(
// 'ws://localhost:3000/cable',
// 'YourChannel',
// myEventHandlerFunction
// ).then(client => {
// client is guaranteed to be initialized properly
// when promise is resolved.
// })
export default class ActionCableClient {
constructor(uri, channel, onMessage) {
this.uri = uri;
this.channel = channel;
this.onMessage = onMessage;
this.socket = new WebSocket(uri);
this.socket.onmessage = this._handleMessage.bind(this);
this._onReadyPromise = new Promise((resolve, reject) => {
this._resolveOnReady = resolve;
this._rejectOnReady= reject;
});
}
static connect(uri, channel, onMessage) {
const instance = new this(uri, channel, onMessage);
return instance.connect();
}
connect() {
this.socket.onopen = () => {
this.socket.send(this._getSubscribePayload())
};
return this._onReadyPromise;
}
_handleMessage(event) {
const msg = JSON.parse(event.data);
if (msg.type === 'confirm_subscription') {
this._resolveOnReady(this);
} else {
this.onMessage(msg);
}
}
_getSubscribePayload() {
return JSON.stringify({
command: 'subscribe',
identifier: JSON.stringify({
channel: this.channel
})
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment