yggdrasil v4.0.0 Yggdrasil.Transformer behaviour View Source
Transformer behaviour that defines how to decode and encode messages from a
Yggdrasil.Channel
.
Small example
Let’s say we want to implement a transformer to send any Elixir term as a string to our subscribers. The transformer module would be implemented as follows:
defmodule Yggdrasil.Transformer.Code do
use Yggdrasil.Transformer
def decode(_channel, message) do
with {decoded, []} <- Code.eval_string(message) do
{:ok, decoded}
else
_ ->
{:error, "Bad message"}
end
end
def encode(_channel, message) do
encoded = inspect(message)
{:ok, encoded}
end
end
And we could use the following Channel
to publish or subscribe to this
messages:
%Channel{
name: "my_channel",
adapter: :redis,
transformer: Yggdrasil.Transformer.Code
}
Transformer alias
When defining transformers it is possible to define aliases for the module as follows:
defmodule Yggdrasil.Transformer.Code do
use Yggdrasil.Transformer, name: :code
(... same implementation as above ...)
end
And adding the following to our application supervision tree:
Supervisor.start_link([
{Yggdrasil.Transformer.Code, []}
...
])
This will allow you to use the following as a Channel
to subscribe and
publish:
%Channel{name: "my_channel", adapter: :redis, transformer: :code}
Link to this section Summary
Functions
Macro for using Yggdrasil.Transformer
Generic message
decoder for a channel
Generic message
encoder for a channel
Callbacks
Callback to define how to decode the message
s coming from a channel
Callback to define how to encode the message
s going to a channel
Link to this section Functions
Macro for using Yggdrasil.Transformer
.
The following are the available options:
:name
- Name of the transformer. Must be an atom.
decode(Yggdrasil.Channel.t(), term()) :: {:ok, term()} | {:error, term()}
Generic message
decoder for a channel
.
encode(Yggdrasil.Channel.t(), term()) :: {:ok, term()} | {:error, term()}
Generic message
encoder for a channel
.
Link to this section Callbacks
decode(channel :: Yggdrasil.Channel.t(), message :: term()) :: {:ok, term()} | {:error, term()}
Callback to define how to decode the message
s coming from a channel
.
encode(channel :: Yggdrasil.Channel.t(), message :: term()) :: {:ok, term()} | {:error, term()}
Callback to define how to encode the message
s going to a channel
.