Skip to content

Commit

Permalink
feat: added OnePiece.Commanded.EventStore.JsonbSerializer module (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
yordis authored Apr 12, 2023
1 parent 6456f52 commit 10b9716
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
4 changes: 4 additions & 0 deletions apps/one_piece_commanded/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

## v0.16.0 - 2023-04-11

- Added `OnePiece.Commanded.EventStore.JsonbSerializer` module.

## v0.15.2 - 2023-03-14

- Fix casting already cast structs in `OnePiece.Commanded.ValueObject`.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
defmodule OnePiece.Commanded.EventStore.JsonbSerializer do
@moduledoc """
A JSONB serializer based on events defined by `OnePiece.Commanded.Event`.
It uses `OnePiece.Commanded.Event` to cast the event to the correct type, by proxying, using `Ecto.Schema`s and
`Ecto.Changeset`s.
## Configuring
To use this serializer, add it to your `config.exs`:
config :my_app, MyApp.EventStore,
serializer: OnePiece.Commanded.EventStore.JsonbSerializer,
types: EventStore.PostgresTypes
"""

alias Commanded.EventStore.TypeProvider

@doc """
Serialize given term to JSON binary data.
It is just a passthrough, since `EventStore.PostgresTypes` will take care of the serialization.
"""
def serialize(term), do: term

@doc """
Deserialize given JSON binary data to the expected type.
It is already a map since `EventStore.PostgresTypes` will take care of the deserialization. Then, it will use
`OnePiece.Commanded.Event` to cast the event to the correct type.
"""
def deserialize(term, config \\ [])

def deserialize(term, config) do
case Keyword.get(config, :type) do
nil ->
term

type ->
type
|> TypeProvider.to_struct()
|> run_casting(term)
end
end

defp run_casting(%module_name{} = _event, term) do
module_name.new!(term)
end
end
2 changes: 1 addition & 1 deletion apps/one_piece_commanded/mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ defmodule OnePiece.Commanded.MixProject do
use Mix.Project

@app :one_piece_commanded
@version "0.15.2"
@version "0.16.0"
@elixir_version "~> 1.13"
@source_url "https://github.com/straw-hat-team/beam-monorepo"

Expand Down

0 comments on commit 10b9716

Please sign in to comment.