Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
defmodule JasonChannelSerializer do
@behaviour Phoenix.Transports.Serializer
alias Phoenix.Socket.{Reply, Message, Broadcast}
@doc """
Translates a `Phoenix.Socket.Broadcast` into a `Phoenix.Socket.Message`.
"""
def fastlane!(%Broadcast{topic: topic, event: event, payload: payload}) do
data = [nil, nil, topic, event, payload]
{:socket_push, :text, Jason.encode_to_iodata!(data)}
end
@doc """
Encodes a `Phoenix.Socket.Message` struct to JSON string.
"""
def encode!(%Reply{join_ref: join_ref, ref: ref, topic: topic, status: status, payload: payload}) do
data = [join_ref, ref, topic, "phx_reply", %{status: status, response: payload}]
{:socket_push, :text, Jason.encode_to_iodata!(data)}
end
def encode!(%Message{join_ref: join_ref, ref: ref, topic: topic, event: event, payload: payload}) do
data = [join_ref, ref, topic, event, payload]
{:socket_push, :text, Jason.encode_to_iodata!(data)}
end
@doc """
Decodes JSON String into `Phoenix.Socket.Message` struct.
"""
def decode!(raw_msg, _opts) do
[join_ref, ref, topic, event, payload | _] = Jason.decode!(raw_msg)
%Phoenix.Socket.Message{
topic: topic,
event: event,
payload: payload,
ref: ref,
join_ref: join_ref,
}
end
end
## replace the transport :websocket, ... line to specify serializers
transport :websocket, Phoenix.Transports.WebSocket,
check_origin: false,
serializer: [{Phoenix.Transports.WebSocketSerializer, "~> 1.0.0"}, {JasonChannelSerializer, "~> 2.0.0"}]
@smedegaard

This comment has been minimized.

Copy link

@smedegaard smedegaard commented Nov 29, 2018

@michalmuskala is this compatible with Phoenix 1.4?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.