在FromJSON

时间:2017-04-08 20:30:31

标签: haskell yesod

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

-- 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默认值。

1 个答案:

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

    -- ...