1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
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
|