Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Message backend with user-friendly errors #29

Merged
merged 8 commits into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 56 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,25 @@ UserContract.conform(%{name: "Jane", age: 21})
# {:ok, %{name: "Jane", age: 21}}

UserContract.conform(%{name: "", age: 21})
# {:error, [error: {[:name], :filled?, [""]}]}
# {:error,
# [
# %Drops.Contract.Messages.Error.Type{
# path: [:name],
# text: "must be filled",
# meta: %{args: [""], predicate: :filled?}
# }
# ]}

UserContract.conform(%{name: "Jane", age: 12})
# {:error, [error: {[:age], :gt?, [18, 12]}]}
# {:error,
# [
# %Drops.Contract.Messages.Error.Type{
# path: [:age],
# text: "must be greater than 18",
# meta: %{args: [18, 12], predicate: :gt?}
# }
# ]}

```

### Nested schemas
Expand Down Expand Up @@ -192,12 +207,20 @@ UserContract.conform(%{
})
# {:error,
# [
# error: {[:user, :address, :zipcode], :filled?, [""]},
# error: {[:user, :tags, 1, :created_at], :type?, [:integer, nil]}
# %Drops.Contract.Messages.Error.Type{
# path: [:user, :address, :zipcode],
# text: "must be filled",
# meta: %{args: [""], predicate: :filled?}
# },
# %Drops.Contract.Messages.Error.Type{
# path: [:user, :tags, 1, :created_at],
# text: "must be an integer",
# meta: %{args: [:integer, nil], predicate: :type?}
# }
# ]}
```

### Type casting
### Type-safe casting

You can define custom type casting functions that will be applied to the input data before it's validated. This is useful when you want to convert the input data to a different format, for example, when you want to convert a string to an integer. Here's an example:

Expand All @@ -215,8 +238,27 @@ end
UserContract.conform(%{count: "1"})
# {:ok, %{count: 1}}

UserContract.conform(%{count: nil})
# [
# %Drops.Contract.Messages.Error.Caster{
# error: %Drops.Contract.Messages.Error.Type{
# path: [:count],
# text: "must be a string",
# meta: %{args: [:string, nil], predicate: :type?}
# }
# }
# ]}

UserContract.conform(%{count: "-1"})
# {:error, [error: {[:count], :gt?, [0, -1]}]}
# {:error,
# [
# %Drops.Contract.Messages.Error.Type{
# path: [:count],
# text: "must be greater than 0",
# meta: %{args: [0, -1], predicate: :gt?}
# }
# ]}

```

It's also possible to define a custom casting module and use it via `caster` option:
Expand Down Expand Up @@ -274,13 +316,6 @@ UserContract.conform(%{
%{"name" => "blue"}
]
})
# {:ok,
# %{
# name: "Jane",
# age: 21,
# tags: [%{name: "red"}, %{name: "green"}, %{name: "blue"}]
# }}

# {:ok,
# %{
# name: "Jane",
Expand Down Expand Up @@ -320,5 +355,12 @@ UserContract.conform(%{email: nil, login: "jane"})
# {:ok, %{email: nil, login: "jane"}}

UserContract.conform(%{email: nil, login: nil})
# {:error, [error: "email or login must be provided"]}
# {:error,
# [
# %Drops.Contract.Messages.Error.Rule{
# path: [],
# text: "email or login must be present",
# meta: %{}
# }
# ]}
```
14 changes: 14 additions & 0 deletions examples/contract/errors-01.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
defmodule UserContract do
use Drops.Contract

schema do
%{
required(:name) => string(:filled?),
required(:email) => string(:filled?)
}
end
end

errors = UserContract.conform(%{name: "", email: 312}) |> UserContract.errors()

Enum.map(errors, &to_string/1)
22 changes: 22 additions & 0 deletions examples/contract/messages-01.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
defmodule MyBackend do
use Drops.Contract.Messages.Backend

def text(:type?, type, input) do
"#{inspect(input)} received but it must be a #{type}"
end

def text(:filled?, _input) do
"cannot be empty"
end
end
defmodule UserContract do
use Drops.Contract, message_backend: MyBackend

schema do
%{
required(:name) => string(:filled?),
required(:email) => string(:filled?)
}
end
end
UserContract.conform(%{name: "", email: 312}) |> UserContract.errors()
10 changes: 10 additions & 0 deletions examples/contract/rule-01.exs
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,15 @@ defmodule UserContract do
end

UserContract.conform(%{email: "[email protected]", login: nil})

UserContract.conform(%{email: nil, login: "jane"})

UserContract.conform(%{email: nil, login: nil})
# {:error,
# [
# %Drops.Contract.Messages.Error.Rule{
# path: [],
# text: "email or login must be present",
# meta: %{}
# }
# ]}
5 changes: 0 additions & 5 deletions examples/readme/contracts-01.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,5 @@ defmodule UserContract do
end

UserContract.conform(%{name: "Jane", email: "[email protected]"})
# {:ok, %{name: "Jane", email: "[email protected]"}}

UserContract.conform(%{email: 312})
# {:error, [error: {[], :has_key?, [:name]}]}

UserContract.conform(%{name: "Jane", email: 312})
# {:error, [error: {[:email], :type?, [:string, 312]}]}
18 changes: 16 additions & 2 deletions examples/readme/schemas-03.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,21 @@ UserContract.conform(%{name: "Jane", age: 21})
# {:ok, %{name: "Jane", age: 21}}

UserContract.conform(%{name: "", age: 21})
# {:error, [error: {[:name], :filled?, [""]}]}
# {:error,
# [
# %Drops.Contract.Messages.Error.Type{
# path: [:name],
# text: "must be filled",
# meta: %{args: [""], predicate: :filled?}
# }
# ]}

UserContract.conform(%{name: "Jane", age: 12})
# {:error, [error: {[:age], :gt?, [18, 12]}]}
# {:error,
# [
# %Drops.Contract.Messages.Error.Type{
# path: [:age],
# text: "must be greater than 18",
# meta: %{args: [18, 12], predicate: :gt?}
# }
# ]}
12 changes: 10 additions & 2 deletions examples/readme/schemas-04.ex
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ UserContract.conform(%{
})
# {:error,
# [
# error: {[:user, :address, :zipcode], :filled?, [""]},
# error: {[:user, :tags, 1, :created_at], :type?, [:integer, nil]}
# %Drops.Contract.Messages.Error.Type{
# path: [:user, :address, :zipcode],
# text: "must be filled",
# meta: %{args: [""], predicate: :filled?}
# },
# %Drops.Contract.Messages.Error.Type{
# path: [:user, :tags, 1, :created_at],
# text: "must be an integer",
# meta: %{args: [:integer, nil], predicate: :type?}
# }
# ]}
20 changes: 19 additions & 1 deletion examples/readme/schemas-05.ex
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,23 @@ end
UserContract.conform(%{count: "1"})
# {:ok, %{count: 1}}

UserContract.conform(%{count: nil})
# [
# %Drops.Contract.Messages.Error.Caster{
# error: %Drops.Contract.Messages.Error.Type{
# path: [:count],
# text: "must be a string",
# meta: %{args: [:string, nil], predicate: :type?}
# }
# }
# ]}

UserContract.conform(%{count: "-1"})
# {:error, [error: {[:count], :gt?, [0, -1]}]}
# {:error,
# [
# %Drops.Contract.Messages.Error.Type{
# path: [:count],
# text: "must be greater than 0",
# meta: %{args: [0, -1], predicate: :gt?}
# }
# ]}
74 changes: 59 additions & 15 deletions lib/drops/contract.ex
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ defmodule Drops.Contract do
...> end
iex> UserContract.conform(%{name: "Jane", age: 48})
{:ok, %{name: "Jane", age: 48}}
iex> UserContract.conform(%{name: "Jane", age: "not an integer"})
{:error, [error: {[:age], :type?, [:integer, "not an integer"]}]}
iex> {:error, errors} = UserContract.conform(%{name: "Jane", age: "not an integer"})
iex> Enum.map(errors, &to_string/1)
["age must be an integer"]

"""
@doc since: "0.1.0"
Expand All @@ -34,18 +35,59 @@ defmodule Drops.Contract do
@callback conform(data :: map(), schema :: Types.Map, keyword()) ::
{:ok, map()} | {:error, list()}

defmacro __using__(_opts) do
@doc """
Return errors from results returned by `conform/2`.

## Examples

iex> defmodule UserContract do
...> use Drops.Contract
...>
...> schema do
...> %{
...> required(:name) => string(:filled?),
...> required(:email) => string(:filled?)
...> }
...> end
...> end
iex> {:error, errors} = UserContract.conform(%{name: "", email: 312})
{:error,
[
%Drops.Contract.Messages.Error.Type{
path: [:email],
text: "must be a string",
meta: %{args: [:string, 312], predicate: :type?}
},
%Drops.Contract.Messages.Error.Type{
path: [:name],
text: "must be filled",
meta: %{args: [""], predicate: :filled?}
}
]
}
iex> Enum.map(errors, &to_string/1)
["email must be a string", "name must be filled"]

"""
@doc since: "0.1.0"
@callback errors({:ok, map()}) :: []
@callback errors({:error, map()}) :: [Drops.Contract.Messages.Error.t()]

defmacro __using__(opts) do
quote do
use Drops.Validator

alias Drops.Types
alias Drops.Contract.Messages

import Drops.Contract
import Drops.Contract.Runtime
import Drops.Types.Map.DSL

@behaviour Drops.Contract

@message_backend unquote(opts[:message_backend]) || Messages.DefaultBackend

Module.register_attribute(__MODULE__, :rules, accumulate: true)

@before_compile Drops.Contract.Runtime
Expand Down Expand Up @@ -73,7 +115,7 @@ defmodule Drops.Contract do
{:ok, value}

{:error, error} = right_errors ->
{:error, {:or, {left_errors, right_errors}}}
{:error, @message_backend.errors({:or, {left_errors, right_errors}})}
end
end
end
Expand All @@ -87,7 +129,7 @@ defmodule Drops.Contract do
all_errors = schema_errors ++ rule_errors

if length(all_errors) > 0 do
{:error, collapse_errors(all_errors)}
{:error, @message_backend.errors(collapse_errors(all_errors))}
else
{:ok, output}
end
Expand Down Expand Up @@ -172,6 +214,9 @@ defmodule Drops.Contract do

defp nest_errors(errors, root) when is_list(errors) do
Enum.map(errors, fn
%{__struct__: _error_type} = error ->
Messages.Error.Conversions.nest(error, root)

{:error, {path, name, args}} ->
{:error, nest_errors({path, name, args}, root)}

Expand Down Expand Up @@ -276,7 +321,7 @@ defmodule Drops.Contract do
...> }
...> end
...> end
iex> UserContract.conform(%{
iex> {:error, errors} = UserContract.conform(%{
...> "user" => %{
...> "name" => "John",
...> "age" => 21,
Expand All @@ -287,7 +332,8 @@ defmodule Drops.Contract do
...> }
...> }
...> })
{:error, [error: {[:user, :address, :street], :filled?, [""]}]}
iex> Enum.map(errors, &to_string/1)
["user.address.street must be filled"]
iex> UserContract.conform(%{
...> "user" => %{
...> "name" => "John",
Expand Down Expand Up @@ -351,7 +397,7 @@ defmodule Drops.Contract do
},
age: 21
}}
iex> UserContract.conform(%{
iex> {:error, errors} = UserContract.conform(%{
...> name: "John",
...> age: "21",
...> address: %{
Expand All @@ -361,11 +407,8 @@ defmodule Drops.Contract do
...> country: "USA"
...> }
...> })
{:error,
[
error: {[:address, :city], :filled?, [""]},
error: {[:age], :type?, [:integer, "21"]}
]}
iex> Enum.map(errors, &to_string/1)
["address.city must be filled", "age must be an integer"]
"""
@spec schema(name :: atom()) :: Macro.t()
defmacro schema(name, do: block) when is_atom(name) do
Expand Down Expand Up @@ -405,8 +448,9 @@ defmodule Drops.Contract do
{:ok, %{email: "[email protected]", login: nil}}
iex> UserContract.conform(%{email: nil, login: "jane"})
{:ok, %{email: nil, login: "jane"}}
iex> UserContract.conform(%{email: nil, login: nil})
{:error, ["email or login must be present"]}
iex> {:error, errors} = UserContract.conform(%{email: nil, login: nil})
iex> Enum.map(errors, &to_string/1)
["email or login must be present"]

"""
defmacro rule(name, input, do: block) do
Expand Down
Loading