Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
witai_elixir_weather_bot/lib/weather_client.ex
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
36 lines (29 sloc)
1000 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule EchoBot.WeatherClient do | |
require Logger | |
def get_weather(location) do | |
get_params = %{"q" => location, "appid" => get_openweathermap_appid} | |
url = "http://api.openweathermap.org/data/2.5/weather?" | |
|> create_url(get_params) | |
Logger.info "Fetching weather using #{inspect(url)}" | |
url | |
|> HTTPotion.get | |
|> deserialize | |
end | |
defp create_url(endpoint, %{} = get_params) do | |
Map.keys(get_params) | |
|> Enum.reduce(endpoint, fn(key, url) -> | |
append_to_url(url, key, Map.get(get_params, key)) | |
end) | |
end | |
defp append_to_url(url, _key, ""), do: url | |
defp append_to_url(url, key, param), do: "#{url}&#{key}=#{param}" | |
defp deserialize(%HTTPotion.Response{status_code: 200} = resp) do | |
{:ok, Poison.decode!(resp.body)} | |
end | |
defp deserialize(%HTTPotion.Response{status_code: code} = resp) do | |
{:error, "Invalid status code #{code}", resp} | |
end | |
defp get_openweathermap_appid() do | |
Application.get_env(:openweathermap, :app_id) | |
end | |
end |