solnic / drops

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

Add maybe #23

Closed solnic closed 1 year ago

solnic commented 1 year ago

This adds a new DSL function called maybe which allows you to define a type that can be either nil or the type that is passed to the maybe function:

defmodule TestContract do
  use Drops.Contract

  schema do
    %{required(:test) => maybe(:string)}
  end
end

TestContract.conform(%{test: nil})
# {:ok, %{test: nil}}

TestContract.conform(%{test: "Hello"})
# {:ok, %{test: "Hello"}}

TestContract.conform(%{test: 312})    
# {:error, [error: {[:test], :type?, [:string, 312]}]}

You can also use any extra predicates for the non-nil type checks:

defmodule TestContract do
  use Drops.Contract

  schema do
    %{required(:test) => maybe(:string, [:filled?])}
  end
end

TestContract.conform(%{test: nil})
# {:ok, %{test: nil}}

TestContract.conform(%{test: "Hello"})
# {:ok, %{test: "Hello"}}

TestContract.conform(%{test: ""})    
# {:error, [error: {[:test], :filled?, [""]}]}