From 266b5a27f9278578b92cf8cdc0f95a19cda2d08b Mon Sep 17 00:00:00 2001 From: Iuri Mateus <20242530+iurimateus@users.noreply.github.com> Date: Mon, 22 Jul 2024 23:50:33 -0300 Subject: [PATCH] fix: do not raise on schemas with string keys (#4) --- lib/peri.ex | 4 ++-- test/peri_test.exs | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/peri.ex b/lib/peri.ex index 33473c0..d3b9d66 100644 --- a/lib/peri.ex +++ b/lib/peri.ex @@ -300,7 +300,7 @@ defmodule Peri do end defp enumerable_has_key?(data, key) when is_map(data) do - Map.has_key?(data, key) or Map.has_key?(data, Atom.to_string(key)) + Map.has_key?(data, key) or Map.has_key?(data, (is_binary(key) && key) || Atom.to_string(key)) end defp enumerable_has_key?(data, key) when is_list(data) do @@ -334,7 +334,7 @@ defmodule Peri do defp get_enumerable_value(enum, key) do case Access.get(enum, key) do - nil when is_map(enum) -> Map.get(enum, Atom.to_string(key)) + nil when is_map(enum) -> Map.get(enum, (is_binary(key) && key) || Atom.to_string(key)) val -> val end end diff --git a/test/peri_test.exs b/test/peri_test.exs index 4a22949..086433c 100644 --- a/test/peri_test.exs +++ b/test/peri_test.exs @@ -9,6 +9,12 @@ defmodule PeriTest do email: {:required, :string} }) + defschema(:simple_mixed_keys, %{ + "email" => {:required, :string}, + name: :string, + age: :integer + }) + defschema(:nested, %{ user: %{ name: :string, @@ -68,6 +74,13 @@ defmodule PeriTest do } = simple(data) end + + test "does not raise on simple schema with string keys" do + data = %{name: "John", age: 30} + + assert {:error, [%Peri.Error{path: ["email"], message: "is required"}]} = + simple_mixed_keys(data) + end end describe "nested schema validation" do