defmodule Cepis.Health do @moduledoc """ The response of `GET /health`. Good for two things: checking that the API answers, and knowing **which version of the database** is live. The DNE database changes every two weeks; `dne` identifies it. """ defstruct status: "", dne: "", ceps: 0, geo: 0, base_gerada_em: "" @type t :: %__MODULE__{ status: String.t(), dne: String.t(), ceps: non_neg_integer(), geo: non_neg_integer(), base_gerada_em: String.t() } @doc """ `true` when the API reports itself healthy. """ @spec ok?(t()) :: boolean() def ok?(%__MODULE__{status: status}), do: status == "ok" @doc false @spec from_map(map()) :: t() def from_map(data) when is_map(data) do %__MODULE__{ status: text(data, "status"), dne: text(data, "dne"), ceps: count(data, "ceps"), geo: count(data, "geo"), base_gerada_em: text(data, "base_gerada_em") } end defp text(data, key) do case Map.get(data, key) do value when is_binary(value) -> value value when is_number(value) -> to_string(value) _ -> "" end end defp count(data, key) do case Map.get(data, key) do value when is_integer(value) -> value value when is_float(value) -> trunc(value) value when is_binary(value) -> case Integer.parse(value) do {number, _} -> number :error -> 0 end _ -> 0 end end end