-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
websocket_serializer.ex
50 lines (42 loc) · 1.23 KB
/
websocket_serializer.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
42
43
44
45
46
47
48
49
50
defmodule Phoenix.Transports.WebSocketSerializer do
@moduledoc false
@behaviour Phoenix.Transports.Serializer
alias Phoenix.Socket.Reply
alias Phoenix.Socket.Message
alias Phoenix.Socket.Broadcast
@doc """
Translates a `Phoenix.Socket.Broadcast` into a `Phoenix.Socket.Message`.
"""
def fastlane!(%Broadcast{} = msg) do
msg = %Message{topic: msg.topic, event: msg.event, payload: msg.payload}
{:socket_push, :text, encode_v1_fields_only(msg)}
end
@doc """
Encodes a `Phoenix.Socket.Message` struct to JSON string.
"""
def encode!(%Reply{} = reply) do
msg = %Message{
topic: reply.topic,
event: "phx_reply",
ref: reply.ref,
payload: %{status: reply.status, response: reply.payload}
}
{:socket_push, :text, encode_v1_fields_only(msg)}
end
def encode!(%Message{} = msg) do
{:socket_push, :text, encode_v1_fields_only(msg)}
end
@doc """
Decodes JSON String into `Phoenix.Socket.Message` struct.
"""
def decode!(message, _opts) do
message
|> Poison.decode!()
|> Phoenix.Socket.Message.from_map!()
end
defp encode_v1_fields_only(%Message{} = msg) do
msg
|> Map.take([:topic, :event, :payload, :ref])
|> Poison.encode_to_iodata!()
end
end