Skip to content

Commit 0d10758

Browse files
committed
fix fasten hook to properly return errors
1 parent f3c70cf commit 0d10758

File tree

2 files changed

+58
-2
lines changed

2 files changed

+58
-2
lines changed

lib/construct/hooks/fasten.ex

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,19 @@ defmodule Construct.Hooks.Fasten do
6363
cast_clause =
6464
quote do
6565
defp unquote(function_name)(%{unquote(to_string(name)) => term}, opts) do
66-
Construct.Type.cast(unquote(type), term, opts)
66+
case Construct.Type.cast(unquote(type), term, opts) do
67+
{:ok, term} -> {:ok, term}
68+
{:error, reason} -> {:error, %{unquote(name) => reason}}
69+
:error -> {:error, %{unquote(name) => :invalid}}
70+
end
6771
end
6872

6973
defp unquote(function_name)(%{unquote(name) => term}, opts) do
70-
Construct.Type.cast(unquote(type), term, opts)
74+
case Construct.Type.cast(unquote(type), term, opts) do
75+
{:ok, term} -> {:ok, term}
76+
{:error, reason} -> {:error, %{unquote(name) => reason}}
77+
:error -> {:error, %{unquote(name) => :invalid}}
78+
end
7179
end
7280
end
7381

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
defmodule Construct.Integration.Hooks.FastenTest do
2+
use Construct.TestCase
3+
4+
defmodule IP do
5+
@behaviour Construct.Type
6+
7+
def cast(term) when is_binary(term) do
8+
:inet.parse_address(String.to_charlist(term))
9+
end
10+
11+
def cast(_) do
12+
:error
13+
end
14+
end
15+
16+
defmodule User do
17+
use Construct
18+
use Construct.Hooks.Fasten
19+
20+
structure do
21+
field :huid, :string
22+
field :ip, IP
23+
end
24+
end
25+
26+
test "#make returns structs with anonymous functions" do
27+
params = %{
28+
"huid" => "9767dcf6-9413-44dd-af9a-2af0188ae12b",
29+
"ip" => "127.0.0.1"
30+
}
31+
32+
assert {:ok, %User{
33+
huid: params["huid"],
34+
ip: {127, 0, 0, 1}
35+
}} == User.make(params)
36+
end
37+
38+
test "#make with invalid params" do
39+
assert {:error, %{huid: :invalid}} =
40+
User.make(%{"huid" => 42, "ip" => 42})
41+
42+
assert {:error, %{huid: :invalid}} =
43+
User.make(%{"huid" => 42, "ip" => "127.0.0.1.1"})
44+
45+
assert {:error, %{ip: :einval}} =
46+
User.make(%{"huid" => "9767dcf6-9413-44dd-af9a-2af0188ae12b", "ip" => "127.0.0.1.1"})
47+
end
48+
end

0 commit comments

Comments
 (0)