是否有方便的方法使用Haskell Persistent执行模型验证?

时间:2014-01-06 18:17:38

标签: haskell persistent convenience-methods

有没有办法在每个update/replaceinsert之前执行自定义验证(某种类型的挂钩),并在验证失败时返回一条消息?就像可以在ActiveModel中完成。

我可以写一个验证函数,但我需要重写我更新或插入此模型的所有地方。

1 个答案:

答案 0 :(得分:1)

AFAIK持久性没有任何内置的验证钩子,这就是我使用的(与yesod' s i18n结合):

-- | Represents an entity that has validation logic
class Validatable e where

    -- | A set of validations and error messages for a
    --   given entity.
    validations :: e -> [(Bool, AppMessage)]
    validations _ = []

    -- | Validate an entity and respond with a Bool wrapped in
    --   a writer with potential error messages. By default this
    --   makes use of @validations e@
    validate :: e -> (Bool, [AppMessage])
    validate e = runWriter $ foldM folder True $ validations e
      where
        folder a (v, m) | v = return $ a && True
                        | otherwise = tell [m] >> return False

并定义您的验证:

instance Validatable Stock where
    validations e = [ ((0<) . stockInventory $ e, MsgPurchaseErrorInventoryNegative)
                    , ((0<) . unMoney . stockPrice $ e, MsgPurchaseErrorPriceNegative)
                    , (maybe True ((0<) . unMoney) . stockCostPrice $ e, MsgPurchaseErrorCostPriceNegative)
                    , ((2<=) . length . stockName $ e, MsgPurchaseErrorNameTooShort)
                    ]

然后在你的处理程序中:

let (isvalid, errors) = validate s
unless isvalid $ invalidArgsI errors