Skip to content

Commit

Permalink
Make type shortcuts work with cast(...)
Browse files Browse the repository at this point in the history
  • Loading branch information
solnic committed Oct 11, 2023
1 parent a5aa5d7 commit e8bdaed
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
14 changes: 13 additions & 1 deletion lib/drops/types/map/dsl.ex
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,14 @@ defmodule Drops.Types.Map.DSL do
{:type, {type, predicates}}
end

def type({:cast, {input_type, cast_opts}}, output_type) do
def type({:cast, {input_type, cast_opts}}, output_type) when is_atom(output_type) do
{:cast, {type(input_type), type(output_type), cast_opts}}
end

def type({:cast, {input_type, cast_opts}}, output_type) do
{:cast, {type(input_type), output_type, cast_opts}}
end

@doc ~S"""
Returns a list type specification.
Expand Down Expand Up @@ -227,6 +231,10 @@ defmodule Drops.Types.Map.DSL do
type(:string, predicates)
end

def string({:cast, _} = cast_spec, predicates \\ []) do
type(cast_spec, string(predicates))
end

@doc ~S"""
Returns an integer type specification.
Expand Down Expand Up @@ -269,6 +277,10 @@ defmodule Drops.Types.Map.DSL do
type(:integer, predicates)
end

def integer({:cast, _} = cast_spec, predicates \\ []) do
type(cast_spec, integer(predicates))
end

@doc ~S"""
Returns a map type specification.
Expand Down
16 changes: 14 additions & 2 deletions test/contract/casters_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,19 @@ defmodule Drops.CastersTest do
describe ":integer => :string" do
contract do
schema do
%{required(:test) => cast(:integer) |> type(:string)}
%{required(:test) => cast(:integer) |> string()}
end
end

test "defining a required key with coercion", %{contract: contract} do
assert {:ok, %{test: "12"}} = contract.conform(%{test: 12})
end
end

describe ":integer => :string with constraints" do
contract do
schema do
%{required(:test) => cast(:integer) |> string()}
end
end

Expand All @@ -18,7 +30,7 @@ defmodule Drops.CastersTest do
describe ":string => :integer" do
contract do
schema do
%{required(:test) => cast(:string) |> type(:integer)}
%{required(:test) => cast(:string) |> integer()}
end
end

Expand Down

0 comments on commit e8bdaed

Please sign in to comment.