From 3f96dfff271281b04d122a980d6c1ab6a5f27380 Mon Sep 17 00:00:00 2001 From: Georgy Shabunin Date: Wed, 25 Sep 2024 11:44:01 +0100 Subject: [PATCH] Handle nil values in transformations (#7) --- lib/transforms/to_integer.ex | 4 +++- lib/transforms/trim.ex | 4 +++- mix.exs | 2 +- test/absinthe_helpers/transforms/to_integer_test.exs | 6 ++++++ test/absinthe_helpers/transforms/trim_test.exs | 6 ++++++ 5 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/transforms/to_integer.ex b/lib/transforms/to_integer.ex index 1dfa5a7..6b3ff6a 100644 --- a/lib/transforms/to_integer.ex +++ b/lib/transforms/to_integer.ex @@ -14,7 +14,9 @@ defmodule AbsintheHelpers.Transforms.ToInteger do @behaviour AbsintheHelpers.Transform - def call(%{data: data} = item, _opts) when is_binary(data) do + def call(item = %{data: nil}, _opts), do: {:ok, item} + + def call(item = %{data: data}, _opts) when is_binary(data) do case Integer.parse(data) do {int, ""} -> {:ok, %{item | data: int}} _ -> {:error, :invalid_integer, %{}} diff --git a/lib/transforms/trim.ex b/lib/transforms/trim.ex index bc10357..0a1e107 100644 --- a/lib/transforms/trim.ex +++ b/lib/transforms/trim.ex @@ -16,7 +16,9 @@ defmodule AbsintheHelpers.Transforms.Trim do @behaviour AbsintheHelpers.Transform - def call(%{data: data} = item, _opts) when is_binary(data) do + def call(item = %{data: nil}, _opts), do: {:ok, item} + + def call(item = %{data: data}, _opts) when is_binary(data) do {:ok, %{item | data: String.trim(data)}} end diff --git a/mix.exs b/mix.exs index b59b3fa..8e9e8d7 100644 --- a/mix.exs +++ b/mix.exs @@ -4,7 +4,7 @@ defmodule AbsintheHelpers.MixProject do def project do [ app: :absinthe_helpers, - version: "0.1.6", + version: "0.1.7", elixir: "~> 1.16", start_permanent: Mix.env() == :prod, deps: deps(), diff --git a/test/absinthe_helpers/transforms/to_integer_test.exs b/test/absinthe_helpers/transforms/to_integer_test.exs index 9f253e1..c311fd8 100644 --- a/test/absinthe_helpers/transforms/to_integer_test.exs +++ b/test/absinthe_helpers/transforms/to_integer_test.exs @@ -3,6 +3,12 @@ defmodule AbsintheHelpers.Transforms.ToIntegerTest do alias AbsintheHelpers.Transforms.ToInteger + test "to_integer transformation on nil value" do + input = %{data: nil} + + assert {:ok, %{data: nil}} = ToInteger.call(input, []) + end + test "to_integer transformation on valid string" do input = %{data: "123"} diff --git a/test/absinthe_helpers/transforms/trim_test.exs b/test/absinthe_helpers/transforms/trim_test.exs index 18fc5a6..d2528e8 100644 --- a/test/absinthe_helpers/transforms/trim_test.exs +++ b/test/absinthe_helpers/transforms/trim_test.exs @@ -3,6 +3,12 @@ defmodule AbsintheHelpers.Transforms.TrimTest do alias AbsintheHelpers.Transforms.Trim + test "trim transformation on nil value" do + input = %{data: nil} + + assert {:ok, %{data: nil}} = Trim.call(input, []) + end + test "trim transformation on string" do input = %{data: " hello "}