Skip to content

Commit

Permalink
Handle nil values in transformations (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
twist900 authored Sep 25, 2024
1 parent a2aa09a commit 3f96dff
Show file tree
Hide file tree
Showing 5 changed files with 19 additions and 3 deletions.
4 changes: 3 additions & 1 deletion lib/transforms/to_integer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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, %{}}
Expand Down
4 changes: 3 additions & 1 deletion lib/transforms/trim.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
6 changes: 6 additions & 0 deletions test/absinthe_helpers/transforms/to_integer_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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"}

Expand Down
6 changes: 6 additions & 0 deletions test/absinthe_helpers/transforms/trim_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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 "}

Expand Down

0 comments on commit 3f96dff

Please sign in to comment.