Current section
Files
Jump to
Current section
Files
priv/templates/graphql_mutations.eex
defmodule <%= inspect @mutations_module %> do
@moduledoc """
Generated by Caravela from <%= inspect @domain_module %>.
Absinthe mutations for every entity. For each entity:
* `create_<singular>` — accepts a typed input object
* `update_<singular>` — takes id + typed input
* `delete_<singular>` — takes id, returns the removed entity
All mutations delegate to the generated context module, which
enforces authorization and lifecycle hooks.
Regenerate with `mix caravela.gen.graphql <%= inspect @domain_module %>`.
Custom code placed below the `# --- CUSTOM ---` marker is preserved.
"""
use Absinthe.Schema.Notation
alias <%= inspect @context_module %>
<%= for e <- @entities do %> input_object <%= inspect e.input_name %> do
<%= for f <- e.input_fields do %> field <%= inspect f.gql_name %>, <%= f.gql_type %>
<% end %> end
<% end %>
object :<%= @mutations_field %> do
<%= for e <- @entities do %> @desc "Create a <%= e.singular %>"
field <%= inspect e.create_field %>, <%= inspect e.gql_name %> do
arg :input, non_null(<%= inspect e.input_name %>)
resolve fn _parent, %{input: input}, resolution ->
case <%= @context_short %>.<%= e.create_fn %>(input, extract_context(resolution)) do
{:ok, entity} -> {:ok, entity}
{:error, reason} -> {:error, format_error(reason)}
end
end
end
@desc "Update a <%= e.singular %>"
field <%= inspect e.update_field %>, <%= inspect e.gql_name %> do
arg :id, non_null(:id)
arg :input, non_null(<%= inspect e.input_name %>)
resolve fn _parent, %{id: id, input: input}, resolution ->
context = extract_context(resolution)
case <%= @context_short %>.<%= e.get_fn %>(id, context) do
nil ->
{:error, "not_found"}
entity ->
case <%= @context_short %>.<%= e.update_fn %>(entity, input, context) do
{:ok, updated} -> {:ok, updated}
{:error, reason} -> {:error, format_error(reason)}
end
end
end
end
@desc "Delete a <%= e.singular %>"
field <%= inspect e.delete_field %>, <%= inspect e.gql_name %> do
arg :id, non_null(:id)
resolve fn _parent, %{id: id}, resolution ->
context = extract_context(resolution)
case <%= @context_short %>.<%= e.get_fn %>(id, context) do
nil ->
{:error, "not_found"}
entity ->
case <%= @context_short %>.<%= e.delete_fn %>(entity, context) do
{:ok, removed} -> {:ok, removed}
{:error, reason} -> {:error, format_error(reason)}
end
end
end
end
<% end %> end
# --- Internal --------------------------------------------------------
defp extract_context(%{context: context}) when is_map(context), do: context
defp extract_context(_), do: %{}
defp format_error(:unauthorized), do: "unauthorized"
defp format_error(%Ecto.Changeset{} = cs), do: inspect(cs.errors)
defp format_error(other), do: inspect(other)
<%= @custom_marker %>