{-|
Module      : Neptune.Utils
Description : Neptune Client
Copyright   : (c) Jiasen Wu, 2020
License     : BSD-3-Clause
-}
module Neptune.Utils where

import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Network.HTTP.Client        as NH
import           RIO

import           Neptune.Backend.Client

-- | Unwrap the 'MimeResult a'. Raise an error if it indicates a failure.
handleMimeError :: (Monad m, HasCallStack) => MimeResult a -> m a
handleMimeError :: MimeResult a -> m a
handleMimeError MimeResult a
result =
    case MimeResult a -> Either MimeError a
forall res. MimeResult res -> Either MimeError res
mimeResult MimeResult a
result of
      Left MimeError
e -> let err_msg :: String
err_msg = MimeError -> String
mimeError MimeError
e
                    response :: ByteString
response = Response ByteString -> ByteString
forall body. Response body -> body
NH.responseBody (Response ByteString -> ByteString)
-> Response ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ MimeError -> Response ByteString
mimeErrorResponse MimeError
e
                in String -> m a
forall a. HasCallStack => String -> a
error (String
err_msg String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" " String -> String -> String
forall a. [a] -> [a] -> [a]
++ ByteString -> String
BSL.unpack ByteString
response)
      Right a
r -> a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
r