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 `rule` macro #3

Closed solnic closed 1 year ago

solnic commented 1 year ago

This adds support for defining arbitrary rule functions that match against input that was already processed and validated by the contract's schema. This allows you to define additional validation logic that can be implemented in a type-safe fashion.

defmodule TestContract do
  use Drops.Contract

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

  rule(:unique?, [{:ok, {:name, value}}]) do
    case value do
      "John" -> {:error, {:taken, :name, value}}
      _ -> :ok
    end
  end
end

TestContract.conform(%{name: "Jane"})
# {:ok, %{name: "Jane"}}

TestContract.conform(%{name: "John"})
# {:error, [error: {:taken, :name, "John"}]}