Reputation: 585
I'd like to define a constraint on a field so reserved words are not valid. How can I accomplish this in Yesod?
{-# LANGUAGE TemplateHaskell #-}
module Sid where
import Control.Exception
import Data.List
import Database.Persist.TH
import Data.Aeson.TH
import Text.Show
import Text.Read
import Data.Text
data Sid = Sid Text
deriving (Show, Read)
reserved :: [Text]
reserved = ["abc","def"]
allowedSid :: Text -> Sid
allowedSid a = (assert (notElem a reserved)) Sid a
derivePersistField "allowedSid"
deriveJSON defaultOptions ''allowedSid
Upvotes: 4
Views: 156
Reputation: 31315
I'd do this in normal Haskell instead: create a newtype wrapper with some smart constructors. This would look something like:
newtype Sid = Sid Text
mkSid :: Text -> Maybe Sid
mkSid t = if t `elem` reserved then Nothing else Just t
Put this code in a module, and don't export the Sid
data constructor.
Upvotes: 4