module Network.Api.Support.Request (
RequestTransformer
, setApiKey
, setUrlEncodedBody
, setQueryParams
, setHeaders
, setHeader
, addHeader
, stripHeader
, setCookieJar
, setMethod
, setBody
, setBodyLazy
, setJson
, (<>)
) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Data.Aeson
import Data.CaseInsensitive
import Data.Monoid
import Data.Time
import Network.HTTP.Client
type RequestTransformer = Endo Request
setApiKey :: B.ByteString -> RequestTransformer
setApiKey key = Endo $ applyBasicAuth key ""
setUrlEncodedBody :: [(B.ByteString, B.ByteString)] -> RequestTransformer
setUrlEncodedBody = Endo . urlEncodedBody
setQueryParams :: [(B.ByteString, Maybe B.ByteString)] -> RequestTransformer
setQueryParams = Endo . setQueryString
setHeaders :: [(CI B.ByteString, B.ByteString)] -> RequestTransformer
setHeaders hs = Endo $ \r -> r { requestHeaders = hs }
setHeader :: (CI B.ByteString, B.ByteString) -> RequestTransformer
setHeader h = stripHeader (fst h) <> addHeader h
addHeader :: (CI B.ByteString, B.ByteString) -> RequestTransformer
addHeader h = Endo $ \r -> r { requestHeaders = requestHeaders r ++ [h] }
stripHeader :: CI B.ByteString -> RequestTransformer
stripHeader n = (Endo $ \r -> r {
requestHeaders = filter (\x -> fst x == n) (requestHeaders r)
})
setCookieJar :: CookieJar -> UTCTime -> RequestTransformer
setCookieJar cj now = Endo $ \r -> fst $ insertCookiesIntoRequest r cj now
setMethod :: B.ByteString -> RequestTransformer
setMethod m = Endo $ \r -> r { method = m }
setBody :: B.ByteString -> RequestTransformer
setBody b = Endo $ \r -> r { requestBody = RequestBodyBS b }
setBodyLazy :: BL.ByteString -> RequestTransformer
setBodyLazy b = Endo $ \r -> r { requestBody = RequestBodyLBS b }
setJson :: ToJSON a => a -> RequestTransformer
setJson v = setHeader ("Content-Type", "application/json") <>
(setBodyLazy . encode . toJSON $ v)
#if __GLASGOW_HASKELL__ < 704
infixr 5 <>
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
#endif