在 FromJSON 中设置默认值

Set default values in FromJSON

我想为我拥有的模型设置默认值

-- 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

但是,它无法编译,我不确定如何填充 createduser 默认值。

这是我的结局,感谢@basile-henry

--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

    -- ...