Skip to content

Commit

Permalink
Doc update
Browse files Browse the repository at this point in the history
  • Loading branch information
solnic committed Oct 18, 2023
1 parent 3ca819c commit 0279a59
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
14 changes: 14 additions & 0 deletions examples/contract/errors-01.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
defmodule UserContract do
use Drops.Contract

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

errors = UserContract.conform(%{name: "", email: 312}) |> UserContract.errors()

Enum.map(errors, &to_string/1)
35 changes: 35 additions & 0 deletions lib/drops/contract.ex
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,41 @@ defmodule Drops.Contract do
@callback conform(data :: map(), schema :: Types.Map, keyword()) ::
{:ok, map()} | {:error, list()}

@moduledoc """
Return errors from results returned by `conform/2`.
## Examples
iex> defmodule UserContract do
...> use Drops.Contract
...>
...> schema do
...> %{
...> required(:name) => string(:filled?),
...> required(:email) => string(:filled?)
...> }
...> end
...> end
iex> errors = UserContract.conform(%{name: "", email: 312}) |> UserContract.errors()
[
%Drops.Contract.Messages.Error{
path: [:email],
text: "must be a string",
opts: %{args: [:string, 312], predicate: :type?}
},
%Drops.Contract.Messages.Error{
path: [:name],
text: "must be filled",
opts: %{args: [""], predicate: :filled?}
}
]
iex> Enum.map(errors, &to_string/1)
["email must be a string", "name must be filled"]
"""
@callback errors({:ok, map()}) :: []
@callback errors({:error, map()}) :: [Drops.Contract.Messages.Error.t()]

defmacro __using__(opts) do
quote do
use Drops.Validator
Expand Down
2 changes: 2 additions & 0 deletions lib/drops/contract/messages.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ defmodule Drops.Contract.Messages do
defmodule Error do
alias __MODULE__

@type t :: %__MODULE__{}

defstruct [:path, :text, :opts]

defimpl String.Chars, for: Error do
Expand Down

0 comments on commit 0279a59

Please sign in to comment.