【问题标题】:Is there convenient way to perform model validations with Haskell Persistent?是否有使用 Haskell Persistent 执行模型验证的便捷方法?
【发布时间】:2014-01-06 18:17:37
【问题描述】:

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

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

【问题讨论】:

    标签: haskell persistent convenience-methods


    【解决方案1】:

    AFAIK persistent 没有任何用于验证的内置钩子,这是我使用的(结合 yesod 的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 2023-04-02
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多