frekw
Forma - Typespec based data transformation
One of the things I’ve missed since coming to Elixir is a simple way to parse data from an external service (like JSON or MessagePack) into a structure that’s more suitable for my application.
I finally got tired of writing transformations from maps with string keys to structs and stole one of Go’s best ideas.
https://github.com/soundtrackyourbrand/forma
Forma parses a typespec that you provide and tries to shape your input data to fit into that typespec.
For example:
defmodule User do
defstruct [:id, :name, :age, :gender]
@type t :: %__MODULE__{
id: String.t,
name: String.t,
age: non_neg_integer(),
gender: :male | :female | :other | :prefer_not_to_say
}
end
Forma.parse(%{"id" => "1", "name" => "Fredrik", "age" => 30, "gender" => "male"}, User)
# => {:ok, %User{id: "1", name: "Fredrik", age: 30, gender: :male}}
It doesn’t do any parsing of its own, but works great together with e.g Poison or jiffy. It supports most cases I’ve stumbled across thus far, but it’s still pretty early in development.
Feedback, ideas for improvements as well as bug reports are welcome!
Most Liked Responses
Phillipp
That whole GitHub org contains quite a lot of nice Elixir packages.
frekw
You’re correct, the docs are wrong. I’ll update it!
mischov
Correct me if I’m wrong, but it looks like your examples should be returning {:ok, %User{...}} tuples instead of just %User{...}?
What happens if the input data cannot be parsed to the structure? Does parse returns {:error, reason}?








