lib/health_routes/health_controller.ex

defmodule SignificaUtils.HealthController do
  @moduledoc """
  Internal controller to be used by `SignificaUtils.HealthRouter`.
  """
  use Phoenix.Controller, formats: [:text]

  import Ecto.Query

  @doc """
  Route handler that always returns "OK"
  """
  def index(conn, _params) do
    text(conn, "OK")
  end

  @doc """
  Route handler that returns the value of the `Application` env `:app_version` for the `otp_app`
  specified when using `SignificaUtils.HealthRouter`.
  """
  def version(conn, _params) do
    otp_app = get_option(conn, :otp_app)

    text(
      conn,
      Application.get_env(otp_app, :app_version, "unknown")
    )
  end

  @doc """
  Route handler that returns the version of the latest ecto migration (table `schema_migrations`).
  Uses the `repo` specified when using `SignificaUtils.HealthRouter`.
  """
  def db_health(conn, _params) do
    repo = get_option(conn, :repo)

    latest_version =
      from(
        schema_migrations in "schema_migrations",
        select: schema_migrations.version,
        order_by: [desc: schema_migrations.inserted_at],
        limit: 1
      )
      |> repo.one!()

    text(conn, to_string(latest_version))
  end

  defp get_option(conn, option) do
    conn.private
    |> Map.fetch!(:significa_utils_health_opts)
    |> Keyword.fetch!(option)
  end
end