towerops/lib/towerops_web/graphql/resolvers/agent.ex
Graham McIntire 146f5745cf
fix: resolve compilation errors, test failures, and credo issues
- Escape HEEx template braces in GraphQL/API docs with raw(~S[...])
- Fix test assertions for updated marketing copy and UI text
- Extract helper functions in GraphQL resolvers to reduce nesting depth
- Create shared ErrorHelpers module for API controllers
- Fix ETS race condition in brute force whitelist cache for async tests
- Fix property test generators to use ASCII instead of printable unicode
- Add alert_severity helper to site_live/show
- Update accounts fixtures for explicit user confirmation
2026-02-14 12:23:10 -06:00

72 lines
2.2 KiB
Elixir

defmodule ToweropsWeb.GraphQL.Resolvers.Agent do
@moduledoc "GraphQL resolvers for agent queries and mutations."
alias Towerops.Agents
def list(_parent, _args, %{context: %{organization_id: org_id}}) do
agents = Agents.list_organization_agent_tokens(org_id)
{:ok, agents}
end
def list(_parent, _args, _resolution), do: {:error, "Authentication required"}
def get(_parent, %{id: id}, %{context: %{organization_id: org_id}}) do
agent = Agents.get_agent_token!(id)
if agent.organization_id == org_id do
{:ok, agent}
else
{:error, "Agent not found"}
end
rescue
Ecto.NoResultsError -> {:error, "Agent not found"}
end
def get(_parent, _args, _resolution), do: {:error, "Authentication required"}
def create(_parent, %{name: name}, %{context: %{organization_id: org_id}}) do
case Agents.create_agent_token(org_id, name) do
{:ok, agent_token, raw_token} ->
{:ok,
%{
id: agent_token.id,
name: agent_token.name,
enabled: agent_token.enabled,
token: raw_token,
inserted_at: agent_token.inserted_at
}}
{:error, changeset} ->
{:error, format_errors(changeset)}
end
end
def create(_parent, _args, _resolution), do: {:error, "Authentication required"}
def delete(_parent, %{id: id}, %{context: %{organization_id: org_id}}) do
agent = Agents.get_agent_token!(id)
if agent.organization_id == org_id do
case Agents.delete_agent_token(id) do
{:ok, _} -> {:ok, %{success: true, message: "Agent deleted"}}
{:error, _} -> {:ok, %{success: false, message: "Could not delete agent"}}
end
else
{:error, "Agent not found"}
end
rescue
Ecto.NoResultsError -> {:error, "Agent not found"}
end
def delete(_parent, _args, _resolution), do: {:error, "Authentication required"}
defp format_errors(changeset) do
changeset
|> Ecto.Changeset.traverse_errors(fn {msg, opts} ->
Regex.replace(~r"%{(\w+)}", msg, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
|> Enum.map_join("; ", fn {field, messages} -> "#{field}: #{Enum.join(messages, ", ")}" end)
end
end