Skip to content

Commit

Permalink
fix fasten hook to properly return errors
Browse files Browse the repository at this point in the history
  • Loading branch information
artemeff committed Feb 1, 2025
1 parent f3c70cf commit 0d10758
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/construct/hooks/fasten.ex
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,19 @@ defmodule Construct.Hooks.Fasten do
cast_clause =
quote do
defp unquote(function_name)(%{unquote(to_string(name)) => term}, opts) do
Construct.Type.cast(unquote(type), term, opts)
case Construct.Type.cast(unquote(type), term, opts) do
{:ok, term} -> {:ok, term}
{:error, reason} -> {:error, %{unquote(name) => reason}}
:error -> {:error, %{unquote(name) => :invalid}}
end
end

defp unquote(function_name)(%{unquote(name) => term}, opts) do
Construct.Type.cast(unquote(type), term, opts)
case Construct.Type.cast(unquote(type), term, opts) do
{:ok, term} -> {:ok, term}
{:error, reason} -> {:error, %{unquote(name) => reason}}
:error -> {:error, %{unquote(name) => :invalid}}
end
end
end

Expand Down
48 changes: 48 additions & 0 deletions test/integration/hooks/fasten_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
defmodule Construct.Integration.Hooks.FastenTest do
use Construct.TestCase

defmodule IP do
@behaviour Construct.Type

def cast(term) when is_binary(term) do
:inet.parse_address(String.to_charlist(term))
end

def cast(_) do
:error
end
end

defmodule User do
use Construct
use Construct.Hooks.Fasten

structure do
field :huid, :string
field :ip, IP
end
end

test "#make returns structs with anonymous functions" do
params = %{
"huid" => "9767dcf6-9413-44dd-af9a-2af0188ae12b",
"ip" => "127.0.0.1"
}

assert {:ok, %User{
huid: params["huid"],
ip: {127, 0, 0, 1}
}} == User.make(params)
end

test "#make with invalid params" do
assert {:error, %{huid: :invalid}} =
User.make(%{"huid" => 42, "ip" => 42})

assert {:error, %{huid: :invalid}} =
User.make(%{"huid" => 42, "ip" => "127.0.0.1.1"})

assert {:error, %{ip: :einval}} =
User.make(%{"huid" => "9767dcf6-9413-44dd-af9a-2af0188ae12b", "ip" => "127.0.0.1.1"})
end
end

0 comments on commit 0d10758

Please sign in to comment.