{-# LANGUAGE OverloadedStrings #-} {-| Module : Kino.Request Description : Contains code for issuing http requests Contains code for issuing http requests -} module Kino.Request (setMovies, defaultOptions) where import Control.Exception import Control.Lens import Data.Aeson hiding (defaultOptions) import Network.Wreq hiding (Options) import qualified Data.Text as T import qualified Network.Wreq as WR (Options) import Kino.Types import Kino.Misc -- | Sends a request and unwraps the top level respone data structure makeRequest :: (FromJSON a) => String -> WR.Options -> IO (Either T.Text a) makeRequest url opts = do r <- asJSON =<< getWith opts url pure $ case r ^. responseBody of (JSONResponse "ok" _ (Just d)) -> Right d (JSONResponse _ m _) -> Left m -- | Sends a request with the given parameters getMovies :: WR.Options -> IO (Either SomeException (Either T.Text JSONListMovies)) getMovies = try . makeRequest "https://yts.mx/api/v2/list_movies.json" -- | The default options for our requests defaultOptions :: WR.Options defaultOptions = defaults & param "limit" .~ ["50"] & param "page" .~ ["1"] -- | Updates the state given a way to request a new movie listing setMovies :: AppS -> IO AppS setMovies s = do m <- getMovies ((s ^. appReqOpts) & param "page" .~ [T.pack (show (s ^. appPage))]) pure $ case m of (Left e) -> displayMessage s True (displayException e) (Right r) -> case r of (Left t) -> displayMessage s False (T.unpack t) (Right l) -> s & appListing .~ l & appCursor .~ 0 & appExpanded .~ False & appDetails .~ (moviesMovies l !? 0)