-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
defmodule Drops.Contract.Messages do | ||
@moduledoc false | ||
|
||
defmodule Error do | ||
alias __MODULE__ | ||
|
||
defstruct [:path, :text, :opts] | ||
|
||
defimpl String.Chars, for: Error do | ||
def to_string(%Error{text: text}) do | ||
text | ||
end | ||
end | ||
end | ||
|
||
def errors(results) do | ||
Enum.map(results, &error/1) | ||
end | ||
|
||
defp error({:error, {path, predicate, [arg, value] = args}}) do | ||
%Error{ | ||
path: path, | ||
text: text(predicate, arg, value), | ||
opts: %{ | ||
predicate: predicate, | ||
args: args | ||
} | ||
} | ||
end | ||
|
||
defp text(:type?, :integer, _value) do | ||
"must be an integer" | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
defmodule Drops.Contract.MessagesTest do | ||
use Drops.ContractCase | ||
|
||
describe "errors/1" do | ||
contract do | ||
schema do | ||
%{ | ||
required(:name) => string(), | ||
required(:age) => integer() | ||
} | ||
end | ||
end | ||
|
||
test "returns a list with error structs", %{contract: contract} do | ||
result = contract.conform(%{name: "Jane Doe", age: "twenty"}) | ||
|
||
assert [error = %{path: path, opts: opts}] = contract.errors(result) | ||
|
||
assert path == [:age] | ||
assert opts == %{predicate: :type?, args: [:integer, "twenty"]} | ||
assert to_string(error) == "must be an integer" | ||
end | ||
end | ||
end |