module Network.API.TheMovieDB.Internal.HTTP
( apiBaseURL,
defaultImagePrefix,
apiGET,
)
where
import Control.Exception
import Network.API.TheMovieDB.Internal.Settings
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/"
defaultImagePrefix :: Text
defaultImagePrefix = "http://image.tmdb.org/t/p/"
mkAPIRequest :: Settings -> Path -> QueryText -> IO HC.Request
mkAPIRequest Settings {..} path params = do
req <- HC.parseRequest (apiBaseURL ++ path)
return $
req
{ HC.queryString = query,
HC.requestHeaders = headers
}
where
query = renderQuery False . queryTextToQuery $ allParams
headers = [("Accept", "application/json")]
allParams =
params
++ ( second Just
<$> catMaybes
[ Just ("api_key", tmdbKey),
("language",) <$> tmdbLanguage
]
)
apiGET :: HC.Manager -> Settings -> Path -> QueryText -> IO (Either Error Body)
apiGET manager settings path params = do
request <- mkAPIRequest settings 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 _ = return $ Left InvalidKeyError