Use Ecto to turn your JSON payload into deeply-nested Elixir structs. Inspired by this Box snippet.
TL;DR:
see live example
The library provides two modules:
EctoBox
- to define schemasEctoBox.HttpResponseMapper
- a reference implementation suitable for converting responses ofReq
andTesla
into Elixir schemas. It's tiny and you can easily adjust it to your needs.
There are great examples of using Changeset
to validate JSON payloads and convert them into nested structs. But there's also an old thread on Elixir Forum asking if it's an Overkill to use Ecto Schema to map external JSON to structs?.
In fact, Ecto is a double-edged sword capable of mapping both the user's input and the DB representation into Elixir structs.
For example, mongodb_ecto implements Ecto.Adapter behaviour to map BSON to nested Elixir structs:
flowchart TD
subgraph Z["Data flow when querying MongoDB through mongodb_ecto"]
direction LR
BSON --> Ecto.Adapter
Ecto.Adapter --> Elixir_Structs
end
But the true magic of Ecto's recursive data conversion lives in the Ecto.Repo.Schema.load
call.
Can we make this light-weight Ecto magic available for use with Tesla
or Req
HTTP libraries? After all, external APIs returning JSON are not that much different from Mongo DB server returning BSON.
If available in Hex, the package can be installed
by adding ecto_box
to your list of dependencies in mix.exs
:
def deps do
[
{:ecto_box, "~> 0.1.0"}
]
end
Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/ecto_box.
Thanks to the contributors of mongodb_ecto repository and @teamon. EctoBox is largely based on their ideas and code snippets.
Please use Github Issues for bug reports and to discuss the improvement proposals.