在Github Issue 上有更多关于这个问题的讨论,我在这里添加它作为答案,因为它更加充实。下面是我们使用下面定义的辅助函数得到的 Handler 函数:
postDataCommentR :: Handler Value
postDataCommentR = do
value <- requireJsonBody' -- Parse request body into Value
commentJson <- requireJsonKey "data" value -- Lookup a key from the Value
comment <- (requireJsonParse commentJson :: Handler Comment) -- Parse the Value into a comment record
insertedComment <- runDB $ insertEntity comment
returnJson insertedComment
这些函数获取请求正文并将其解析为 aeson Value:
import qualified Data.Aeson as J
import qualified Data.Aeson.Parser as JP
import Data.Conduit.Attoparsec (sinkParser)
-- These two functions were written by @FtheBuilder
parseJsonBody' :: (MonadHandler m) => m (J.Result Value)
parseJsonBody' = do
eValue <- rawRequestBody $$ runCatchC (sinkParser JP.value')
return $ case eValue of
Left e -> J.Error $ show e
Right value -> J.Success value
-- | Same as 'parseJsonBody', but return an invalid args response on a parse
-- error.
requireJsonBody' :: (MonadHandler m) => m Value
requireJsonBody' = do
ra <- parseJsonBody'
case ra of
J.Error s -> invalidArgs [pack s]
J.Success a -> return a
这些辅助函数用于将 Value 解析为记录:
requireJsonParse :: (MonadHandler m, FromJSON a) => Value -> m a
requireJsonParse v = case J.fromJSON v of
J.Error s -> invalidArgs [pack s]
J.Success a -> return a
requireJsonKey :: (MonadHandler m) => Text -> Value -> m Value
requireJsonKey key jObject@(Object hashMap) = case lookup key hashMap of
Nothing -> invalidArgs ["Couldn't find a value when looking up the key " <> key <> " in the object: " <> (pack (show jObject))]
Just v -> return v
requireJsonKey key invalid = invalidArgs ["When looking up the key " <> key <> ", expected an object but got a " ++ (pack (show invalid))]
评论
艾森镜头
我没有使用aeson-lens,但无论有没有它,代码都非常相似,因为我们只是深入一键。如果我们更深入地遍历 JSON,aeson-lens 会让事情变得更好。
与包装器定义的比较
一旦你定义了辅助函数,你还有几行代码来解析Value,然后查找data 键,然后创建你的记录。您可以做一些事情来缩短它,但最终@Carsten 推荐的包装器将具有相似的长度,但复杂性更小,imo。