aboutsummaryrefslogtreecommitdiff
path: root/src/Tomato/Retrieve.hs
diff options
context:
space:
mode:
authorJacques Comeaux <jacquesrcomeaux@gmail.com>2022-05-29 16:07:59 -0500
committerJacques Comeaux <jacquesrcomeaux@gmail.com>2022-05-29 16:07:59 -0500
commit8a06c083fab9c66e754c7ed5a75dd4d89131c43e (patch)
tree28098c165bce0d8ebb5dda2d5390e63ddca1ab1e /src/Tomato/Retrieve.hs
parent399ab3ee1653bbc0da69e2cc299aa2a313e765b4 (diff)
Improve error reporting
Diffstat (limited to 'src/Tomato/Retrieve.hs')
-rw-r--r--src/Tomato/Retrieve.hs34
1 files changed, 19 insertions, 15 deletions
diff --git a/src/Tomato/Retrieve.hs b/src/Tomato/Retrieve.hs
index 80bdac6..2f7f20b 100644
--- a/src/Tomato/Retrieve.hs
+++ b/src/Tomato/Retrieve.hs
@@ -10,49 +10,53 @@ import Network.HTTP.Req
( jsonResponse
, bsResponse
, req
+ , Req
+ , runReq
+ , defaultHttpConfig
, NoReqBody (..)
, (/:)
, (=:)
- , Req
, GET (..)
, https
, responseBody
)
-import Data.Tomato (Tomato (..), Links (..))
+import Tomato.App (App (..))
+import Tomato.Data.Except (DecodeException (..))
+import Tomato.Data.Tomato (Tomato (..), Links (..))
import qualified Data.Aeson as Ae
import qualified RIO.ByteString as B
+import qualified RIO.Text as T
--- TODO global config reader monad
-tomatoFile :: FilePath
-tomatoFile = "tomato.png"
-
-clientId :: Text
-clientId = "FbzqI-oR7277JwL1ZGsyUw7yG1F5U0U3WhQ3kOW71Do"
-
-- | Get a random tomato
-randomTomato :: Req ()
+randomTomato :: RIO App ()
randomTomato = queryTomato >>= downloadTomato
-- | Ask for a tomato
-queryTomato :: Req Tomato
+queryTomato :: RIO App Tomato
queryTomato = do
+ clientId <- asks appClientId
let url = https "api.unsplash.com" /: "photos" /: "random"
- js <- req GET url NoReqBody jsonResponse $
+ js <- rr $ req GET url NoReqBody jsonResponse $
"query" =: ("tomato" :: Text) <>
"client_id" =: clientId
tomato <- case Ae.fromJSON (responseBody js) of
Ae.Success r -> pure r
- Ae.Error _s -> error "deal with this later"
+ Ae.Error s -> throwM $ DecodeException $ T.pack s
return tomato
-- | Download a specific tomato
-downloadTomato :: Tomato -> Req ()
+downloadTomato :: Tomato -> RIO App ()
downloadTomato tom = do
+ tomatoFile <- asks appFile
+ clientId <- asks appClientId
let url = download (links tom)
- bs <- req GET url NoReqBody bsResponse $
+ bs <- rr $ req GET url NoReqBody bsResponse $
"query" =: ("tomato" :: Text) <>
"client_id" =: clientId
B.writeFile tomatoFile (responseBody bs)
+
+rr :: Req a -> RIO App a
+rr = runReq defaultHttpConfig