aboutsummaryrefslogtreecommitdiff
path: root/lib/Web/OpenWeatherMap/Client.hs
blob: d760812e41ea8f7756b67f2139c9199e682be181 (plain)
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
{-|
High-level client functions perfoming requests to OpenWeatherMap API.
-}
module Web.OpenWeatherMap.Client
  ( Location(..)
  , getWeather
  , getForecast
  ) where

import Network.HTTP.Client (defaultManagerSettings, newManager)
import Servant.Client
  ( BaseUrl(BaseUrl)
  , ClientEnv
  , ClientError
  , Scheme(Http)
  , mkClientEnv
  , runClientM
  )

import qualified Web.OpenWeatherMap.API as API
import Web.OpenWeatherMap.Types.CurrentWeather (CurrentWeather)
import Web.OpenWeatherMap.Types.ForecastWeather (ForecastWeather)

-- | Various way to specify location.
data Location
  = Name String -- ^ City name.
  | Coord Double
          Double -- ^ Geographic coordinates: latitude and longitude.

-- | Make a request to OpenWeatherMap API
--   and return current weather in given location.
getWeather ::
     String -- ^ API key.
  -> Location
  -> IO (Either ClientError CurrentWeather)
getWeather appid loc = defaultEnv >>= runClientM (api loc appid)
  where
    api (Name city) = API.weatherByName city
    api (Coord lat lon) = API.weatherByCoord lat lon

-- | Make a request to OpenWeatherMap API
--   and return forecast weather in given location.
getForecast ::
     String -- ^ API key.
  -> Location
  -> IO (Either ClientError ForecastWeather)
getForecast appid loc = defaultEnv >>= runClientM (api loc appid)
  where
    api (Name city) = API.forecastByName city
    api (Coord lat lon) = API.forecastByCoord lat lon

defaultEnv :: IO ClientEnv
defaultEnv = do
  manager <- newManager defaultManagerSettings
  return $ mkClientEnv manager baseUrl

-- XXX openweathermap.org does not support HTTPS,
-- XXX appid is passed in clear text. Oops.
baseUrl :: BaseUrl
baseUrl = BaseUrl Http "api.openweathermap.org" 80 "/data/2.5"