2014-01-06 10 views
4

update/replace 또는 insert 전에 사용자 지정 유효성 검사 (어떤 종류의 후크)를 수행하고 유효성 검사가 실패 할 때 메시지를 반환하는 방법이 있습니까? 마치 ActiveModel에서 할 수있는 것처럼.Haskell Persistent로 모델 검증을 수행하는 편리한 방법이 있습니까?

나는 단지 검증 기능을 쓸 수 있었지만이 모델을 업데이트하거나 삽입 한 모든 곳을 다시 작성해야합니다.

-- | 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 [email protected] 
    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 

을 그리고 정의하여 검증 :

답변

1

영구 AFAIK 유효성 검사에 대한 내장 후크가 없습니다, 이것이 내가 (yesod의 국제화와 결합)을 사용하는 것입니다

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