module Network.API.TheMovieDB.Internal.HTTP
( apiGET
) where
import Control.Applicative
import Control.Exception
import Network.API.TheMovieDB.Internal.Types
import qualified Network.HTTP.Client as HC
import Network.HTTP.Types
apiBaseURL :: String
apiBaseURL = "https://api.themoviedb.org/3/"
mkAPIRequest :: Key -> Path -> QueryText -> IO HC.Request
mkAPIRequest key path params = do
req <- HC.parseUrl (apiBaseURL ++ path)
return $ req { HC.queryString = query
, HC.requestHeaders = headers
}
where
query = renderQuery False . queryTextToQuery $ allParams
allParams = params ++ [("api_key", Just key)]
headers = [("Accept", "application/json")]
apiGET :: HC.Manager -> Key -> Path -> QueryText -> IO (Either Error Body)
apiGET manager key path params = do
request <- mkAPIRequest key path params
response <- catch (Right <$> HC.httpLbs request manager) httpError
return $ case response of
Left e -> Left e
Right r
| statusIsSuccessful (HC.responseStatus r) -> Right (HC.responseBody r)
| otherwise -> Left (ServiceError . show $ HC.responseStatus r)
where
httpError :: HC.HttpException -> IO (Either Error (HC.Response Body))
httpError e = return $ case e of
HC.StatusCodeException (Status 401 _) _ _ -> Left InvalidKeyError
_ -> Left (HttpExceptionError e)