Packages

Aerfoirt is a library for airport data.

Current section

Files

Jump to
aerfoirt lib aerfoirt.ex
Raw

lib/aerfoirt.ex

defmodule Aerfoirt do
@moduledoc ~S"""
Helps gather a find date about aiports
"""
require Logger
@doc"""
Takes and IATA code. Returns true if the airport exists, otherwise false.
"""
def exists?(code), do: :ets.member(ets_table, code)
def ets_table, do: :airport_data
@doc"""
Returns a list of all of the airports.
"""
def list do
:ets.match(ets_table, :"$1")
|> Enum.map(&to_struct/1)
|> Enum.reject(&is_nil/1)
end
def lookup(code) do
case :ets.lookup(ets_table, code) do
[{_, airport}] -> to_struct(airport)
_ -> nil
end
end
@doc"""
Loads the airport data from the SITA api
"""
def load do
Logger.debug("Requesting new data from the Airport API: #{data_url}")
case HTTPoison.get(data_url, [{"Accept", "application/json"}]) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
body
|> parse_body
|> read_body
|> Enum.each(&(:ets.insert(ets_table, &1)))
{:ok, %HTTPoison.Response{status_code: 404}} ->
Logger.error("Airport API responded with 404")
{:error, %HTTPoison.Error{reason: reason}} ->
Logger.error("Error when talking to Aiport API: #{inspect reason}")
end
end
@doc"""
Returns the API key
"""
def sita_api_key,
do: System.get_env("SITA_API_KEY") || Application.get_env(:aerfoirt, :sita_api_key)
defp data_url, do: "https://airport.api.aero/airport?user_key=#{sita_api_key}"
# Parses the API response
defp parse_body(json) do
case Poison.decode(json) do
{:ok, body} -> body
{:error, reason} -> Logger.error("Error parsing data from Airport API: #{inspect reason}")
end
end
# Maps all of the airport objects from a successful response into a map
defp read_body(%{"airports" => airports, "success" => true}) do
Enum.reduce(airports, Map.new, fn(airport, map) ->
Map.put_new(map, airport["code"], to_tuple(airport))
end)
end
defp to_struct([{_code, airport}]), do: to_struct(airport)
defp to_struct({code, name, city, country, timezone, coords}) do
%Aerfoirt.Airport{code: code, name: name, city: city, country: country, timezone: timezone, coords: coords}
end
defp to_struct(_), do: nil
# Transforms a JSON object from the API response into a tuple for ETS
defp to_tuple(%{"code" => code, "name" => name, "city" => city, "country" => country,
"timezone" => timezone, "lat" => lat, "lng" => lng}) do
{code, name, city, country, timezone, [lng, lat]}
end
end