chandlr-server/app/DataClient.hs

36 lines
1.1 KiB
Haskell
Raw Normal View History

2024-03-23 01:27:12 +00:00
module DataClient
2024-03-23 01:43:24 +00:00
( fetchLatest
)
where
import Data.Time.Clock (UTCTime)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Char8 as LC8
2024-03-23 01:27:12 +00:00
2024-03-23 01:43:24 +00:00
import Common.Network.CatalogPostType (CatalogPost)
import Common.Network.ClientTypes (Model (..), FetchCatalogArgs (..))
2024-03-23 01:27:12 +00:00
import Common.Network.HttpClient
2024-03-23 01:43:24 +00:00
( post
, HttpError (..)
)
import Data.Aeson (eitherDecode, encode, FromJSON)
import Common.Server.JSONSettings (JSONSettings)
2024-03-23 01:27:12 +00:00
2024-03-23 01:43:24 +00:00
fetchLatest :: JSONSettings -> Model -> UTCTime -> IO (Either HttpError [ CatalogPost ])
fetchLatest settings m t = do
2024-03-23 01:27:12 +00:00
post settings "/rpc/fetch_catalog" payload False >>= return . eitherDecodeResponse
where
payload = encode FetchCatalogArgs
{ max_time = t
, max_row_read = fetchCount m
}
2024-03-23 01:43:24 +00:00
eitherDecodeResponse :: (FromJSON a) => Either HttpError LBS.ByteString -> Either HttpError a
eitherDecodeResponse (Left err) = Left err
eitherDecodeResponse (Right bs) =
case eitherDecode bs of
Right val -> Right val
Left err -> Left $ StatusCodeError 500 $ LC8.pack $ "Failed to decode JSON: " ++ err ++ " " ++ (show bs)