Last active
January 10, 2016 18:48
-
-
Save terakilobyte/1f3c930cc0ac540f185f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
defmodule Votio.TopicChannel do | |
use Votio.Web, :channel | |
use Guardian.Channel | |
def join("topics:lobby", %{claims: claim, resource: resource}, socket) do | |
{:ok, %{ message: "Joined"}, socket} | |
end | |
def join("topics:lobby", _, socket) do | |
{:error, %{error: "authentication required"}} | |
end | |
def handle_in("ping", _payload, socket) do | |
user = Guardian.Channel.current_resource(socket) | |
push socket, "pong", %{ message: "pong", from: user.email} | |
{:reply, :ok, socket} | |
end | |
# It is also common to receive messages from the client and | |
# broadcast to everyone in the current topic (votes:lobby). | |
def handle_in("shout", payload, socket) do | |
broadcast socket, "shout", payload | |
{:noreply, socket} | |
end | |
# This is invoked every time a notification is being broadcast | |
# to the client. The default implementation is just to push it | |
# downstream but one could filter or change the event. | |
def handle_out(event, payload, socket) do | |
push socket, event, payload | |
{:noreply, socket} | |
end | |
end |
This file contains hidden or 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
defmodule Votio.TopicChannelTest do | |
use Votio.ChannelCase | |
alias Votio.TopicChannel | |
import Votio.Factory | |
setup do | |
user = create(:user) | |
{:ok, jwt, full_claims} = Guardian.encode_and_sign(user) | |
{:ok, _, socket} = | |
socket() | |
|> subscribe_and_join(TopicChannel, "topics:lobby", %{"guardian_token" => "#{jwt}"}) | |
{:ok, socket: socket} | |
end | |
test "ping replies with status ok", %{socket: socket} do | |
ref = push socket, "ping", %{} | |
assert_reply ref, :ok, _ | |
end | |
test "shout broadcasts to topics:lobby", %{socket: socket} do | |
push socket, "shout", %{"hello" => "all"} | |
assert_broadcast "shout", %{"hello" => "all"} | |
end | |
test "broadcasts are pushed to the client", %{socket: socket} do | |
broadcast_from! socket, "broadcast", %{"some" => "data"} | |
assert_push "broadcast", %{"some" => "data"} | |
end | |
test "can't push without being authenticated" do | |
ref = | |
socket() | |
|> join(TopicChannel, "topics:lobby") | |
assert_reply ref, :error, %{error: "not authenticated"} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment