Is there convenient way to perform model validations with Haskell Persistent?

189 views Asked by At

Is there any way to perform custom validations (some kind of hooks) before each update/replace or insert and return a message when validation fails? Just like it can be done in ActiveModel.

I could just write a validating function, but I will need to rewrite all the places where I updated or inserted this model.

1

There are 1 answers

0
Nathan Kot On

AFAIK persistent doesn't have any built-in hooks for validation, this is what I use (combined with 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

And define your validations:

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

And then in your handler:

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