I’m trying to parse a response of a json api by using with
. The problems is Map.fetch/2
returens {:ok, any} | :error
. And with
requires {:ok, any} | {:error, any}
. So I have to indent my code with multiple case
level like following:
def domain_info(url) do
with {:ok, result} <- get("/v1/domain/info", query: [domain: url]) do
case Map.fetch(result, :body) do
{:ok, body} ->
case Map.fetch(body, "code") do
{:ok, code} ->
case code do
100_000 ->
{:ok,
Map.take(body, ["domain", "cname", "status"])
|> Map.update("status", "configuraing", fn cur ->
case cur do
4 -> "online"
6 -> "offline"
_ -> "configuring"
end
end)}
_ ->
{:error, Map.take(body, ["code", "message"])}
end
:error ->
{:error, "no key 'code' in body"}
end
:error ->
{:error, "no key 'body' in response"}
end
end
end
Is there a better way to do that? Our should I create a wrapper for Map.fetch
which returns {:error, nil}
when no such key found.