Stampede.Channels.Serializer behaviour (stampede v1.4.0)

Copy Markdown View Source

Turns messages into WebSocket frames and back.

Stampede.Channels.connect/2 picks Stampede.Channels.Serializer.V2 or Stampede.Channels.Serializer.V1 from its :vsn. A server that extends the protocol with frames of its own can be given a serializer with the :serializer option, usually one that handles those frames and leaves the rest to a built-in one:

defmodule MyApp.Load.Serializer do
  @behaviour Stampede.Channels.Serializer

  alias Stampede.Channels.{Message, Serializer}

  @impl true
  def encode(message), do: Serializer.V2.encode(message)

  @impl true
  def decode({:binary, <<9, size, topic::binary-size(size), data::binary>>}) do
    {:ok, %Message{topic: topic, event: "snapshot", payload: {:binary, data}}}
  end

  def decode(frame), do: Serializer.V2.decode(frame)
end

Summary

Callbacks

Decodes a frame sent by the server, or returns :error to ignore it.

Encodes a message to send to the server.

Types

frame()

@type frame() :: {:text, binary()} | {:binary, binary()}

Callbacks

decode(frame)

@callback decode(frame()) :: {:ok, Stampede.Channels.Message.t()} | :error

Decodes a frame sent by the server, or returns :error to ignore it.

encode(t)

@callback encode(Stampede.Channels.Message.t()) :: frame()

Encodes a message to send to the server.

It may raise, for example when the payload cannot be encoded, and the exception is then raised where the message was pushed.