module Yesod.Request
(
RequestBodyContents
, Request (..)
, RequestReader (..)
, FileInfo (..)
, waiRequest
, languages
, lookupGetParam
, lookupPostParam
, lookupCookie
, lookupFile
, lookupGetParams
, lookupPostParams
, lookupCookies
, lookupFiles
, ParamName
, ParamValue
, ParamError
) where
import qualified Network.Wai as W
import qualified Data.ByteString.Lazy as BL
import Control.Monad.IO.Class
import Control.Monad (liftM)
import Control.Monad.Instances ()
import Data.Maybe (listToMaybe)
type ParamName = String
type ParamValue = String
type ParamError = String
class Monad m => RequestReader m where
getRequest :: m Request
runRequestBody :: m RequestBodyContents
languages :: RequestReader m => m [String]
languages = reqLangs `liftM` getRequest
waiRequest :: RequestReader m => m W.Request
waiRequest = reqWaiRequest `liftM` getRequest
type RequestBodyContents =
( [(ParamName, ParamValue)]
, [(ParamName, FileInfo)]
)
data FileInfo = FileInfo
{ fileName :: String
, fileContentType :: String
, fileContent :: BL.ByteString
}
deriving (Eq, Show)
data Request = Request
{ reqGetParams :: [(ParamName, ParamValue)]
, reqCookies :: [(ParamName, ParamValue)]
, reqWaiRequest :: W.Request
, reqLangs :: [String]
, reqNonce :: Maybe String
}
lookup' :: Eq a => a -> [(a, b)] -> [b]
lookup' a = map snd . filter (\x -> a == fst x)
lookupGetParams :: RequestReader m => ParamName -> m [ParamValue]
lookupGetParams pn = do
rr <- getRequest
return $ lookup' pn $ reqGetParams rr
lookupGetParam :: RequestReader m => ParamName -> m (Maybe ParamValue)
lookupGetParam = liftM listToMaybe . lookupGetParams
lookupPostParams :: RequestReader m
=> ParamName
-> m [ParamValue]
lookupPostParams pn = do
(pp, _) <- runRequestBody
return $ lookup' pn pp
lookupPostParam :: (MonadIO m, RequestReader m)
=> ParamName
-> m (Maybe ParamValue)
lookupPostParam = liftM listToMaybe . lookupPostParams
lookupFile :: (MonadIO m, RequestReader m)
=> ParamName
-> m (Maybe FileInfo)
lookupFile = liftM listToMaybe . lookupFiles
lookupFiles :: RequestReader m
=> ParamName
-> m [FileInfo]
lookupFiles pn = do
(_, files) <- runRequestBody
return $ lookup' pn files
lookupCookie :: RequestReader m => ParamName -> m (Maybe ParamValue)
lookupCookie = liftM listToMaybe . lookupCookies
lookupCookies :: RequestReader m => ParamName -> m [ParamValue]
lookupCookies pn = do
rr <- getRequest
return $ lookup' pn $ reqCookies rr