Created
January 19, 2024 05:08
-
-
Save nallwhy/0ddb3a32f9ccc502ecc06e991ca104a4 to your computer and use it in GitHub Desktop.
IsNil Ash validation (validate the fields are nil)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyApp.Validation.IsNil do | |
use Ash.Resource.Validation | |
alias Ash.Error.Changes.{NoSuchAttribute, InvalidAttribute} | |
@impl true | |
def init(opts) do | |
{:ok, opts} | |
end | |
@impl true | |
def validate(changeset, opts) do | |
fields = Keyword.get(opts, :fields) | |
errors = | |
fields | |
|> Enum.reduce([], fn field, errors -> | |
case changeset.data |> Map.has_key?(field) do | |
false -> | |
error = | |
[resource: changeset.resource, name: field] | |
|> with_description(opts) | |
|> NoSuchAttribute.exception() | |
[error | errors] | |
true -> | |
case changeset.data |> Map.get(field) do | |
nil -> | |
errors | |
_ -> | |
error = | |
[field: field, value: Ash.Changeset.get_attribute(changeset, field)] | |
|> with_description(opts) | |
|> InvalidAttribute.exception() | |
[error | errors] | |
end | |
end | |
end) | |
|> Enum.reverse() | |
case errors do | |
[] -> :ok | |
errors -> {:error, errors} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment