Skip to content

Commit

Permalink
Get field opts when blocks exist
Browse files Browse the repository at this point in the history
  • Loading branch information
martinthenth committed Nov 20, 2024
1 parent 1f53222 commit 7a1c50e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
25 changes: 21 additions & 4 deletions lib/goal.ex
Original file line number Diff line number Diff line change
Expand Up @@ -566,14 +566,19 @@ defmodule Goal do

defmacro optional(name, type, opts) when type in [:map, {:array, :map}] do
children = get_field_children(opts)
field_opts = get_field_options(opts)

quote do
properties = Enum.reduce(unquote(children), %{}, &Map.merge(&2, &1))

if properties == %{} do
%{unquote(name) => [type: unquote(type)]}
%{unquote(name) => [{:type, unquote(type)} | unquote(field_opts)]}
else
%{unquote(name) => [type: unquote(type), properties: properties]}
%{
unquote(name) => [
{:type, unquote(type)} | [{:properties, properties} | unquote(field_opts)]
]
}
end
end
end
Expand All @@ -594,15 +599,19 @@ defmodule Goal do

defmacro required(name, type, opts) when type in [:map, {:array, :map}] do
children = get_field_children(opts)
field_opts = get_field_options(opts)

quote do
properties = Enum.reduce(unquote(children), %{}, &Map.merge(&2, &1))

if properties == %{} do
%{unquote(name) => [type: unquote(type), required: true]}
%{unquote(name) => [{:type, unquote(type)} | [{:required, true} | unquote(field_opts)]]}
else
%{
unquote(name) => [type: unquote(type), required: true, properties: properties]
unquote(name) => [
{:type, unquote(type)}
| [{:required, true} | [{:properties, properties} | unquote(field_opts)]]
]
}
end
end
Expand All @@ -622,6 +631,14 @@ defmodule Goal do
end
end

defp get_field_options(opts) do
if Keyword.has_key?(opts, :do) do
[]
else
opts
end
end

@doc ~S"""
Validates parameters against a validation schema.
Expand Down
8 changes: 6 additions & 2 deletions test/goal_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ defmodule GoalTest do
optional(:paws, :integer)
end
end

required(:list_of_maps, {:array, :map}, min: 1, max: 1)
end

defparams :enums do
Expand Down Expand Up @@ -144,7 +146,8 @@ defmodule GoalTest do
}
]
}
]
],
list_of_maps: [type: {:array, :map}, required: true, min: 1, max: 1]
}
end

Expand Down Expand Up @@ -1165,7 +1168,8 @@ defmodule GoalTest do
schema = %{
list: [
type: {:array, :map},
rules: [min: 1, max: 1]
rules: [min: 1, max: 1],
required: true
]
}

Expand Down

0 comments on commit 7a1c50e

Please sign in to comment.