ash_graphql/lib/resource/transformers/validate_actions.ex

61 lines
1.5 KiB
Elixir
Raw Normal View History

2021-03-09 08:22:41 +13:00
defmodule AshGraphql.Resource.Transformers.ValidateActions do
# Ensures that all referenced actiosn exist
@moduledoc false
2022-08-31 13:08:16 +12:00
use Spark.Dsl.Transformer
2021-03-09 08:22:41 +13:00
2022-08-31 13:08:16 +12:00
alias Spark.Dsl.Transformer
2021-03-09 08:22:41 +13:00
2022-08-31 13:08:16 +12:00
def after_compile?, do: true
def transform(dsl) do
2021-03-09 08:22:41 +13:00
dsl
|> Transformer.get_entities([:graphql, :queries])
|> Enum.concat(Transformer.get_entities(dsl, [:graphql, :mutations]))
|> Enum.each(fn query_or_mutation ->
type =
case query_or_mutation do
%AshGraphql.Resource.Query{} ->
:read
%AshGraphql.Resource.Action{} ->
nil
2021-03-09 08:22:41 +13:00
%AshGraphql.Resource.Mutation{type: type} ->
type
end
2022-08-31 13:08:16 +12:00
available_actions = Transformer.get_entities(dsl, [:actions]) || []
available_actions =
if type do
Enum.filter(available_actions, fn action ->
action.type == type
end)
else
available_actions
end
2022-08-31 13:08:16 +12:00
action =
Enum.find(available_actions, fn action ->
action.name == query_or_mutation.action
end)
unless action do
resource = Transformer.get_persisted(dsl, :module)
raise Spark.Error.DslError,
module: resource,
2021-03-09 08:22:41 +13:00
message: """
No such action #{query_or_mutation.action} of type #{type} on #{inspect(resource)}
Available #{type} actions:
#{Enum.map_join(available_actions, ", ", & &1.name)}
2021-03-09 08:22:41 +13:00
"""
end
end)
{:ok, dsl}
end
end