Skip to content

Instantly share code, notes, and snippets.

@mcrumm
Last active October 22, 2023 13:42
Show Gist options
  • Save mcrumm/88a9e2b7349df4a53aa7d93f61bab7df to your computer and use it in GitHub Desktop.
Save mcrumm/88a9e2b7349df4a53aa7d93f61bab7df to your computer and use it in GitHub Desktop.
Get astronauts in space right now
defmodule Space do
@moduledoc """
Documentation for Space.
"""
@doc """
Hello world.
## Examples
iex> Space.hello()
:world
"""
def hello do
:world
end
@url 'http://api.open-notify.org/astros.json'
def get_astros() do
with {:ok, {{'HTTP/1.1', 200, 'OK'}, _headers, body}} <-
:httpc.request(:get, {@url, []}, [], []),
{:ok, json} <- Jason.decode(body),
{:ok, people} <- parse_result(json) do
print_table(people)
end
end
defp parse_result(%{"message" => "success", "people" => people}) when is_list(people) do
sorted_people =
people
|> Enum.map(fn %{"name" => name} = person ->
[first, last] = String.split(name, " ", parts: 2)
%{"first_name" => first, "last_name" => last, "craft" => person["craft"]}
end)
|> Enum.sort_by(fn %{"last_name" => name} -> name end)
{:ok, sorted_people}
end
defp parse_result(other) do
{:error, "Bad response, #{inspect(other)}"}
end
defp print_table(people) do
IO.puts("There are #{length(people)} people in space right now.")
Scribe.print(people, data: ["last_name", "first_name", "craft"])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment