defmodule SyntropyWeb.Api.RunController do use SyntropyWeb, :controller alias SyntropyWeb.Api.{ControllerHelpers, RunJSON, RunRequest} @spec index(Plug.Conn.t(), map()) :: Plug.Conn.t() def index(conn, params) do limit = ControllerHelpers.limit(params) runs = limit |> Syntropy.recent_runs() |> Enum.map(&RunJSON.run/1) json(conn, %{data: runs}) end @spec show(Plug.Conn.t(), map()) :: Plug.Conn.t() def show(conn, %{"id" => run_id}) do case Syntropy.run(run_id) do nil -> ControllerHelpers.not_found(conn, "Run", run_id) run -> json(conn, %{data: RunJSON.run(run)}) end end @spec create(Plug.Conn.t(), map()) :: Plug.Conn.t() def create(conn, params) do with {:ok, %{prompt: prompt, opts: opts}} <- RunRequest.parse(params), {:ok, run} <- Syntropy.start_run(prompt, opts) do conn |> put_status(:accepted) |> json(%{data: RunJSON.run(run)}) else {:error, errors} when is_list(errors) -> ControllerHelpers.invalid_request(conn, "Invalid run request.", errors) {:error, reason} -> ControllerHelpers.task_failure(conn, reason) end end end