Skip to content

Commit

Permalink
fix: do not fetch peri parser on raw data schemas (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
zoedsoupe committed Aug 2, 2024
1 parent 859a0fd commit 32aa540
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions lib/peri.ex
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,9 @@ defmodule Peri do
{:ok, result} ->
{:ok, result}

{:error, errors} ->
{:error, errors}

{:error, reason, info} ->
{:error, Peri.Error.new_single(reason, info)}
end
Expand Down Expand Up @@ -583,7 +586,9 @@ defmodule Peri do
end

defp validate_field(val, {:cond, condition, true_type, else_type}, parser) do
if condition.(parser.root_data) do
root = maybe_get_root_data(parser)

if condition.(root) do
validate_field(val, true_type, parser)
else
validate_field(val, else_type, parser)
Expand All @@ -592,7 +597,9 @@ defmodule Peri do

defp validate_field(val, {:dependent, callback}, parser)
when is_function(callback, 1) do
with {:ok, type} <- callback.(parser.root_data),
root = maybe_get_root_data(parser)

with {:ok, type} <- callback.(root),
{:ok, schema} <- validate_schema(type) do
validate_field(val, schema, parser)
end
Expand Down Expand Up @@ -725,7 +732,7 @@ defmodule Peri do
end

defp validate_field(data, schema, p) when is_enumerable(data) do
root = p.root_data
root = maybe_get_root_data(p)

case traverse_schema(schema, Peri.Parser.new(data, root_data: root)) do
%Peri.Parser{errors: []} = parser -> {:ok, parser.data}
Expand All @@ -738,6 +745,10 @@ defmodule Peri do
{:error, "expected type of %{expected} received %{actual} value", info}
end

# if schema is matches a raw data structure, it will not use the Peri.Parser
defp maybe_get_root_data(%Peri.Parser{} = p), do: p.root_data
defp maybe_get_root_data(data), do: data

@doc """
Validates a schema definition to ensure it adheres to the expected structure and types.
Expand Down

0 comments on commit 32aa540

Please sign in to comment.