module Network.HTTP.Client.Contrib where

import Data.Aeson
import Data.Bifunctor
import Data.ByteString.Lazy.Char8 qualified as BSL
import Network.HTTP.Conduit
import Network.HTTP.Types qualified as HT

-- | Get response body out of a @Response@
handleResponse :: Response BSL.ByteString -> Either BSL.ByteString BSL.ByteString
handleResponse :: Response ByteString -> Either ByteString ByteString
handleResponse Response ByteString
rsp
  | Status -> Bool
HT.statusIsSuccessful (forall body. Response body -> Status
responseStatus Response ByteString
rsp) = forall a b. b -> Either a b
Right (forall body. Response body -> body
responseBody Response ByteString
rsp)
  -- TODO: better to surface up entire resp so that client can decide what to do when error happens.
  -- e.g. when 404, the response body could be empty hence library user has no idea what's happening.
  -- Which will be breaking changes.
  -- The current work around is surface up entire response as string.
  | ByteString -> Bool
BSL.null (forall body. Response body -> body
responseBody Response ByteString
rsp) = forall a b. a -> Either a b
Left ([Char] -> ByteString
BSL.pack forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> [Char]
show Response ByteString
rsp)
  | Bool
otherwise = forall a b. a -> Either a b
Left (forall body. Response body -> body
responseBody Response ByteString
rsp)

handleResponseJSON ::
  FromJSON a =>
  Response BSL.ByteString ->
  Either BSL.ByteString a
handleResponseJSON :: forall a. FromJSON a => Response ByteString -> Either ByteString a
handleResponseJSON =
  forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either forall a b. a -> Either a b
Left (forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first [Char] -> ByteString
BSL.pack forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. FromJSON a => ByteString -> Either [Char] a
eitherDecode) forall b c a. (b -> c) -> (a -> b) -> a -> c
. Response ByteString -> Either ByteString ByteString
handleResponse