solnic / drops

🛠️ Tools for working with data effectively - data contracts using types, schemas, domain validation rules, type-safe casting, and more.
Other
251 stars 4 forks source link

Add coercions #2

Closed solnic closed 1 year ago

solnic commented 1 year ago

This adds a basic support for coercion functions. The DSL allows you to define from which type you want to coerce and what should be the resulting type. Additional constraints for the input type are not added at this point, but it's as good starting point.

defmodule TestContract do
  use Drops.Contract

  schema do
    %{
      required(:code) => from(:integer) |> type(:string),
      required(:price) => from(:string) |> type(:integer)
    }
  end
end

TestContract.conform(%{code: 12, price: "11"})
# {:ok, %{code: "12", price: 11}}

TestContract.conform(%{code: 12, price: 11})  
# {:error, [error: {:string?, :price, 11}]}