Skip to content

Instantly share code, notes, and snippets.

@sousousore1
Last active July 23, 2018 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sousousore1/e0d23e07eb6a743fe8ad440c1f07d718 to your computer and use it in GitHub Desktop.
Save sousousore1/e0d23e07eb6a743fe8ad440c1f07d718 to your computer and use it in GitHub Desktop.
How to connect to actioncable server via actioncable client of npm package when using devise_token_auth gem.
import ActionCable from 'actioncable'
const buildUrl = (url, parameters) {
var qs = ''
for (var key in parameters) {
var value = parameters[key]
qs += encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&'
}
if (qs.length > 0) {
qs = qs.substring(0, qs.length - 1)
url = url + '?' + qs
}
return url
}
const tokens = {
'access-token': 'xxx',
'client': 'xxx',
'uid': 'xxx'
}
const wsUrl = buildUrl(
'ws://localhost:3000/cable',
tokens
)
const consumer = ActionCable.createConsumer(wsUrl)
const channel = consumer.subscriptions.create({
channel: 'HogeChannel'
}, {
connected: (o) => console.log(o),
disconnected: (o) => console.log(o),
received: (o) => console.log(o),
rejected: (o) => console.log(o)
})
// Send action
channel.perform('hoge')
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
params = request.query_parameters()
access_token = params["access-token"]
uid = params["uid"]
client = params["client"]
self.current_user = find_verified_user(access_token, uid, client)
end
private
def find_verified_user(token, uid, client_id)
user = User.find_by(email: uid)
if user && user.valid_token?(token, client_id)
user
else
reject_unauthorized_connection
end
end
end
end
class HogeChannel < ApplicationCable::Channel
def subscribed
stream_from broadcasting
end
def unsubscribed
end
def hoge
message = 'hogeeee'
ActionCable.server.broadcast broadcasting, message
end
private
def broadcasting
"hoge_channel_#{current_user.id}"
end
end
mount ActionCable.server => '/cable'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment