Skip to content

dicefm/ecto_box

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

EctoBox

Use Ecto to turn your JSON payload into deeply-nested Elixir structs. Inspired by this Box snippet.

TL;DR: see live example

What's in the box?

The library provides two modules:

  • EctoBox - to define schemas
  • EctoBox.HttpResponseMapper - a reference implementation suitable for converting responses of Req and Tesla into Elixir schemas. It's tiny and you can easily adjust it to your needs.

Philosophy

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.

Installation

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.

Acknowledgments

Thanks to the contributors of mongodb_ecto repository and @teamon. EctoBox is largely based on their ideas and code snippets.

Contributing

Please use Github Issues for bug reports and to discuss the improvement proposals.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published