我想为我拥有的模型设置默认值
-- models
Bid
price Int
created UTCTime
user UserId
deriving Eq Show Generic
我希望当前用户设置user
属性,但以下内容不起作用:
instance FromJSON Bid where
parseJSON (Object v) =
Bid <$> v .: "price"
<*> getCurrentTime -- "created" property.
<*> requireAuthId -- "user" property.
parseJSON _ = mzero
但是,它无法编译,我不确定如何填充created
和user
默认值。
答案 0 :(得分:0)
这里是我的结局,感谢{basile-henry的answers
--Models.hs
-- A Bid type that represents the data we will get from JSON.
data SemiBid = SemiBid
{ semiBidPrice :: Int
}
instance FromJSON SemiBid where
parseJSON (Object v) =
SemiBid <$> v .: "price"
parseJSON _ = mzero
然后在我的POST
处理程序中:
postRestfulBidsR :: Handler Value
postRestfulBidsR = do
currentTime <- liftIO getCurrentTime
userId <- requireAuthId
semiBid <- requireJsonBody :: Handler SemiBid
let bid = Bid
{ bidPrice = semiBidPrice semiBid
, bidCreated = currentTime
, bidBidder = userId
}
bidId <- runDB $ insert bid
-- ...