我有一个ajax调用将json发送到Yesod中的路由,我希望路由解析json并将其直接插入数据库.在我的模型文件中
createtime UTCTime default=now()
Run Code Online (Sandbox Code Playgroud)
因为客户端没有发送创建时间,所以这会阻止解析json.我尝试为日志条目编写自己的parseJson,但由于getCurrentTime在IO monad中返回一个值,因此我无法插入UTCTime默认值.如果可能的话,我希望数据库设置值.
在这一点上我唯一能想到的就是创建一个像LogEntryWithoutTime这样的类型,将JSON解析为它并转换为LogEntry.有没有更简单的方法?
编辑: 我显示三个不同的失败,将getCurrentTime添加到JSON解析.首先,目的是解析createtime(如果可用),并默认为服务器上的getCurrentTime.不管怎样,这是不对的,因为我们不应该依赖客户的时间.
instance FromJSON Log where
parseJSON (Object o) = Log
<$> o .: "userid"
...
<*> o .:? "createtime" .!= liftIO getCurrentTime
Run Code Online (Sandbox Code Playgroud)
错误是
Model.hs:58:32:
Couldn't match expected type ‘UTCTime’
with actual type ‘m0 UTCTime’
In the second argument of ‘(.!=)’, namely ‘liftIO getCurrentTime’
In the second argument of ‘(<*>)’, namely
‘o .:? "createtime" .!= liftIO getCurrentTime’
Run Code Online (Sandbox Code Playgroud)
其次,我试着获得当前时间.
<*> liftIO getCurrentTime
Run Code Online (Sandbox Code Playgroud)
我得到了错误
Model.hs:58:9:
No instance for (MonadIO
aeson-0.7.0.6:Data.Aeson.Types.Internal.Parser)
arising from a use of …Run Code Online (Sandbox Code Playgroud)