elixir_channels_demo/lib/demo_web/channels/room_channel.ex

63 lines
1.6 KiB
Elixir

defmodule DemoWeb.RoomChannel do
use DemoWeb, :channel
require Logger
@impl true
def join("room:lobby", payload, socket) do
if authorized?(payload) do
{:ok, socket}
else
{:error, %{reason: "unauthorized"}}
end
end
# Channels can be used in a request/response fashion
# by sending replies to requests from the client
@impl true
def handle_in("ping", payload, socket) do
{:reply, {:ok, payload}, socket}
end
#
# Here is recieved the requests from the client
# we spawn a new process to compute the result, which
# is sent back in a new message when the task is finished
# The new process PID is used as a key for the client to
# associate the result to its request.
# the key(id) is immediatly returned to the client.
#
@impl true
def handle_in("fib", payload, socket) do
me = self()
id = spawn(fn ->
result = Funcs.fib(String.to_integer(payload["query"]))
send(me, {:response, %{id: Kernel.inspect(self()),
query: payload["query"],
result: result}})
end)
{:reply, {:ok, %{id: Kernel.inspect(id)}}, socket}
end
# It is also common to receive messages from the client and
# broadcast to everyone in the current topic (room:lobby).
@impl true
def handle_in("shout", payload, socket) do
broadcast(socket, "shout", payload)
{:noreply, socket}
end
# Add authorization logic here as required.
defp authorized?(_payload) do
true
end
@impl true
def handle_info({:response, map}, socket) do
Logger.debug("send response #{Kernel.inspect map}")
push(socket, "response", map)
{:noreply, socket}
end
end