2020-01-26 20:34:25 +01:00
|
|
|
defmodule Mobilizon.GraphQL.Helpers.Error do
|
2019-02-07 10:27:54 +01:00
|
|
|
@moduledoc """
|
2020-01-26 20:34:25 +01:00
|
|
|
Helper functions for Mobilizon.GraphQL
|
2019-02-07 10:27:54 +01:00
|
|
|
"""
|
2020-06-05 11:38:49 +02:00
|
|
|
alias Ecto.Changeset
|
2019-02-07 10:27:54 +01:00
|
|
|
|
2019-01-25 15:41:10 +01:00
|
|
|
def handle_errors(fun) do
|
|
|
|
fn source, args, info ->
|
|
|
|
case Absinthe.Resolution.call(fun, source, args, info) do
|
2020-06-05 11:38:49 +02:00
|
|
|
{:error, %Changeset{} = changeset} ->
|
|
|
|
format_changeset(changeset)
|
|
|
|
|
|
|
|
{:error, _, %Changeset{} = changeset} ->
|
|
|
|
format_changeset(changeset)
|
|
|
|
|
|
|
|
val ->
|
|
|
|
val
|
2019-01-25 15:41:10 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-06-05 11:38:49 +02:00
|
|
|
def format_changeset(%Changeset{changes: changes} = changeset) do
|
2019-01-25 15:41:10 +01:00
|
|
|
# {:error, [email: {"has already been taken", []}]}
|
2020-06-05 11:38:49 +02:00
|
|
|
|
2019-01-25 15:41:10 +01:00
|
|
|
errors =
|
2020-06-05 11:38:49 +02:00
|
|
|
Enum.reduce(changes, [], fn {_key, value}, acc ->
|
|
|
|
case value do
|
|
|
|
%Changeset{} ->
|
|
|
|
{:error, errors} = format_changeset(value)
|
|
|
|
acc ++ errors
|
|
|
|
|
|
|
|
_ ->
|
|
|
|
acc
|
|
|
|
end
|
2019-01-25 15:41:10 +01:00
|
|
|
end)
|
|
|
|
|
2020-06-05 11:38:49 +02:00
|
|
|
errors = errors ++ Enum.map(changeset.errors, &transform_error/1)
|
|
|
|
|
2019-01-25 15:41:10 +01:00
|
|
|
{:error, errors}
|
|
|
|
end
|
2020-06-05 11:38:49 +02:00
|
|
|
|
|
|
|
defp transform_error({key, {value, _context}}) do
|
|
|
|
[message: "#{value}", details: key]
|
|
|
|
end
|
2019-01-25 15:41:10 +01:00
|
|
|
end
|