module Web.Twitter.Conduit.Request
( Parameters(..)
, APIRequest(..)
, APIQuery
, APIQueryItem
, PV(..)
, makeSimpleQuery
, paramValueBS
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Lens
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S8
import Data.Text (Text)
import qualified Data.Text.Encoding as T
import Data.Time.Calendar (Day)
import Network.HTTP.Client.MultipartFormData
import qualified Network.HTTP.Types as HT
class Parameters a where
params :: Lens' a APIQuery
#if __GLASGOW_HASKELL__ >= 706
#endif
data APIRequest apiName responseType
= APIRequestGet
{ _url :: String
, _params :: APIQuery
}
| APIRequestPost
{ _url :: String
, _params :: APIQuery
}
| APIRequestPostMultipart
{ _url :: String
, _params :: APIQuery
, _part :: [Part]
}
instance Parameters (APIRequest apiName responseType) where
params f (APIRequestGet u pa) = APIRequestGet u <$> f pa
params f (APIRequestPost u pa) = APIRequestPost u <$> f pa
params f (APIRequestPostMultipart u pa prt) =
(\p -> APIRequestPostMultipart u p prt) <$> f pa
instance Show (APIRequest apiName responseType) where
show (APIRequestGet u p) = "APIRequestGet " ++ show u ++ " " ++ show (makeSimpleQuery p)
show (APIRequestPost u p) = "APIRequestPost " ++ show u ++ " " ++ show (makeSimpleQuery p)
show (APIRequestPostMultipart u p _) = "APIRequestPostMultipart " ++ show u ++ " " ++ show (makeSimpleQuery p)
type APIQuery = [APIQueryItem]
type APIQueryItem = (ByteString, PV)
data PV
= PVInteger { unPVInteger :: Integer }
| PVBool { unPVBool :: Bool }
| PVString { unPVString :: Text }
| PVIntegerArray { unPVIntegerArray :: [Integer] }
| PVStringArray { unPVStringArray :: [Text] }
| PVDay { unPVDay :: Day }
deriving (Show, Eq)
makeSimpleQuery :: APIQuery -> HT.SimpleQuery
makeSimpleQuery = traversed . _2 %~ paramValueBS
paramValueBS :: PV -> ByteString
paramValueBS (PVInteger i) = S8.pack . show $ i
paramValueBS (PVBool True) = "true"
paramValueBS (PVBool False) = "false"
paramValueBS (PVString txt) = T.encodeUtf8 txt
paramValueBS (PVIntegerArray iarr) = S8.intercalate "," $ map (S8.pack . show) iarr
paramValueBS (PVStringArray iarr) = S8.intercalate "," $ map T.encodeUtf8 iarr
paramValueBS (PVDay day) = S8.pack . show $ day