module Twfy.Client
(
A.ApiKey
, Client(..)
, client
, getConstituency
, getConstituencies
, getMP
, getMPs
)
where
import Servant.Client hiding(Client(..), client)
import Network.HTTP.Client (Manager, newManager)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Servant.Common.BaseUrl (parseBaseUrl)
import qualified Data.Text as T
import qualified Twfy.Api as A
import Twfy.Data.Constituency
import Twfy.Data.MP
data Client = Client {
clientApiKey :: A.ApiKey
, clientApiUri :: String
, clientManager :: Manager
, clientEnv :: ClientEnv
}
instance Show Client where
show c = let k = show (clientApiKey c)
u = show (clientApiUri c)
in "twfy-client: " ++ k ++ " - " ++ u
client :: A.ApiKey
-> Maybe String
-> Maybe Manager
-> IO Client
client k u m = let defaultUri = "https://www.theyworkforyou.com/api"
defaultManagerAction = newManager tlsManagerSettings
key = k
uri = maybe defaultUri id u
in do
baseUrl <- parseBaseUrl uri
manager <- maybe defaultManagerAction return m
let env = ClientEnv manager baseUrl
return $ Client key uri manager env
getConstituency :: Client
-> Maybe T.Text
-> Maybe T.Text
-> IO (Either ServantError Constituency)
getConstituency c = do
let key = Just $ clientApiKey c
env = clientEnv c
(\name postCode -> (flip runClientM) env (A.getConstituency key name postCode))
getConstituencies :: Client
-> IO (Either ServantError [Constituency])
getConstituencies c = do
let key = Just $ clientApiKey c
env = clientEnv c
(flip runClientM) env (A.getConstituencies key)
getMP :: Client
-> Maybe Int
-> Maybe T.Text
-> Maybe T.Text
-> Maybe Bool
-> IO (Either ServantError MP)
getMP c = do
let key = Just $ clientApiKey c
env = clientEnv c
(\mpId constituencyName postCode alwaysReturn -> (flip runClientM) env (A.getMP key mpId constituencyName postCode alwaysReturn))
getMPs :: Client
-> Maybe T.Text
-> Maybe T.Text
-> Maybe T.Text
-> IO (Either ServantError [MP])
getMPs c = do
let key = Just $ clientApiKey c
env = clientEnv c
(\personName partyName date -> (flip runClientM) env (A.getMPs key personName partyName date))