Packages
eventstore
0.15.1
1.4.8
1.4.7
1.4.6
1.4.4
1.4.3
1.4.2
1.4.1
1.4.0
1.3.2
1.3.1
1.3.0
1.2.3
1.2.2
1.2.1
1.2.0
1.1.0
1.0.3
1.0.2
1.0.1
1.0.0
1.0.0-rc.0
0.17.0
0.16.2
0.16.1
0.16.0
0.15.1
0.15.0
0.14.0
0.14.0-rc.0
0.13.2
0.13.1
0.13.0
0.12.1
0.12.0
0.11.0
0.11.0-rc.0
0.10.1
0.10.0
0.9.0
0.8.1
0.8.0
0.7.4
0.7.3
0.7.2
0.7.1
0.7.0
0.6.2
0.6.1
0.6.0
0.5.2
0.5.1
0.5.0
0.4.3
0.4.2
0.4.1
0.4.0
0.3.0
0.2.1
0.2.0
0.1.0
0.0.5
0.0.4
0.0.3
0.0.2
0.0.1
Event store using PostgreSQL for persistence.
Current section
Files
Jump to
Current section
Files
guides/Event Serialization.md
# Event serialization
The default serialization of event data and metadata uses Erlang's [external term format](http://erlang.org/doc/apps/erts/erl_ext_dist.html). This is not a recommended serialization format for production usage as backwards compatibility is only guaranteed going back at least two major releases.
You must implement the `EventStore.Serializer` behaviour to provide your preferred serialization format.
## Example JSON serializer
The example serializer below serializes event data and metadata to JSON using the [Poison](https://github.com/devinus/poison) library.
```elixir
defmodule JsonSerializer do
@moduledoc """
A serializer that uses the JSON format.
"""
@behaviour EventStore.Serializer
@doc """
Serialize given term to JSON binary data.
"""
def serialize(term) do
Poison.encode!(term)
end
@doc """
Deserialize given JSON binary data to the expected type.
"""
def deserialize(binary, config) do
type = case Keyword.get(config, :type, nil) do
nil -> []
type -> type |> String.to_existing_atom |> struct
end
Poison.decode!(binary, as: type)
end
end
```
Configure your serializer by setting the `serializer` option in the mix environment configuration file (e.g. `config/dev.exs`).
```elixir
config :eventstore, EventStore.Storage,
serializer: JsonSerializer,
# ...
```
You must set the `event_type` field to a string representing the type of event being persisted when using this serializer:
```elixir
%EventStore.EventData{
event_type: "Elixir.ExampleEvent",
data: %ExampleEvent{key: "value"},
metadata: %{user: "someuser@example.com"},
}
```
You can use `Atom.to_string/1` to get a string representation of a given event struct compatible with the example `JsonSerializer` module:
```elixir
event = %ExampleEvent{key: "value"}
event_type = Atom.to_string(event.__struct__) #=> "Elixir.ExampleEvent"
```