module Network.StackExchange.Response
(
SEException(..), askSE
, se
) where
import Control.Applicative ((<$>))
import Control.Exception (Exception, throwIO)
import Data.Maybe (fromMaybe)
import Data.Typeable (Typeable)
import Control.Lens
import Data.Aeson (Value(..))
import Data.ByteString.Lazy (ByteString, toStrict)
import Data.Default (Default(..))
import Data.Text.Lazy.Encoding (encodeUtf8)
import qualified Network.HTTP.Conduit as C
import Network.StackExchange.Request
data SEException = SEException
{ _data ∷ ByteString
, _error ∷ String
} deriving (Show, Typeable)
instance Exception SEException
askSE ∷ Request Ready n r → IO r
askSE q = do
let R {_method, _parse} = unwrap q def
r ← C.withManager $ \m → C.parseUrl (render q) >>= \url →
C.responseBody <$> C.httpLbs (url {C.method = toStrict $ encodeUtf8 _method}) m
case _parse of
Just f → return $ f r
Nothing → throwIO $
SEException r "libstackexchange.askSE: no parsing function registered"
se ∷ (Functor f, Isomorphic k) ⇒ k (SE a → f (SE a)) (Maybe Value → f (Maybe Value))
se = iso to' from'
where
to' = SE . fromMaybe Null
from' (SE Null) = Nothing
from' (SE x) = Just x