-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathroom_channel.ex
41 lines (36 loc) · 1.1 KB
/
room_channel.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
defmodule ChatWeb.RoomChannel do
use ChatWeb, :channel
def join("room:lobby", payload, socket) do
if authorized?(payload) do
send(self(), :after_join)
{: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
def handle_in("ping", payload, socket) do
{:reply, {:ok, payload}, socket}
end
# It is also common to receive messages from the client and
# broadcast to everyone in the current topic (chat_room:lobby).
def handle_in("shout", payload, socket) do
Chat.Message.changeset(%Chat.Message{}, payload) |> Chat.Repo.insert
broadcast socket, "shout", payload
{:noreply, socket}
end
# example see: https://git.io/vNsYD
def handle_info(:after_join, socket) do
Chat.Message.get_messages()
|> Enum.each(fn msg -> push(socket, "shout", %{
name: msg.name,
message: msg.message,
}) end)
{:noreply, socket} # :noreply
end
# Add authorization logic here as required.
defp authorized?(_payload) do
true
end
end