您可以使用它allParams
来访问您在日志中看到的完整请求参数。
对于像这样的请求:
barcode=5555555555555&name=Pancake&ingredients=milk&ingredients=egg
我们可以allParams
这样使用:
action MyAction = do
let ingredients = allParams
-- ingredients = [("barcode",Just "5555555555555"),("name",Just "Pancake"),("ingredients",Just "milk"),("ingredients",Just "egg")]
我们仍然需要过滤此列表以仅返回成分值:
action MyAction = do
let ingredients = allParams
|> filter (\(paramName, paramValue) -> paramName == "ingredients")
-- ingredients = [("ingredients",Just "milk"),("ingredients",Just "egg")]
现在我们需要将此键值映射映射到值。因为值是可能(如Just "milk"
),我们将使用mapMaybe
而不是map
。mapMaybe
丢弃所有Nothing
值并解包Just
:
action MyAction = do
let ingredients = allParams
|> filter (\(paramName, paramValue) -> paramName == "ingredients")
|> mapMaybe (\(paramName, paramValue) -> paramValue)
-- ingredients = ["milk", "ingredients"]
我们有一个[ByteString]
现在。我们处理的大多数函数都期望 aText
而不是 a ByteString
,因此让我们使用cs
(cs 是转换字符串的缩写) 进行转换:
action MyAction = do
let ingredients :: [Text] = allParams
|> filter (\(paramName, paramValue) -> paramName == "ingredients")
|> mapMaybe (\(paramName, paramValue) -> paramValue)
|> map cs
-- ingredients = ["milk", "ingredients"]
将其移至Application/Controller/Helper.hs
对于一个很好的代码结构,我会将此函数移出Application/Controller/Helper.hs
如下:
module Application.Helper.Controller
( ...
, paramList -- Don't forget the export :)
)
paramList name = allParams
|> filter (\(paramName, paramValue) -> paramName == name)
|> mapMaybe (\(paramName, paramValue) -> paramValue)
|> map cs
然后像这样在控制器中使用它:
action MyAction = do
let ingredients = paramList "ingredients"
中的所有功能Application.Helper.Controller
都在我们的控制器中自动可用。