git.iko.soy/typeable/http-api-data
on master help sign in
Add an example for non-default FormOptions
commite613d050e206add3bca1b7acaf98e997b444ff4a authorNickolay Kudasov <nickolay.kudasov@gmail.com> dateWed 31 Aug 2016, 03:45 (10 years ago) parent2df7799
1 file changed+32−2
src/Web/Internal/FormUrlEncoded.hs+32−2
src/Web/Internal/FormUrlEncoded.hs+32−2
@@ -68,11 +68,16 @@ import Web.Internal.HttpApiData
6868-- >>> :set -XFlexibleContexts
6969-- >>> :set -XScopedTypeVariables
7070-- >>> :set -XTypeFamilies
71−-- >>> import Data.Either (isLeft)
72−-- >>> import Data.List (sort)
71+-- >>> import Data.Char (toLower)
72+--
7373-- >>> data Person = Person { name :: String, age :: Int } deriving (Show, Generic)
7474-- >>> instance ToForm Person
7575-- >>> instance FromForm Person
76+--
77+-- >>> data Project = Project { projectName :: String, projectSize :: Int } deriving (Generic, Show)
78+-- >>> myOptions = FormOptions { fieldLabelModifier = map toLower . drop (length ("project" :: String)) }
79+-- >>> instance ToForm Project where toForm = genericToForm myOptions
80+-- >>> instance FromForm Project where fromForm = genericFromForm myOptions
7681
7782-- | Typeclass for types that can be used as keys in a 'Form'-like container (like 'Map').
7883class ToFormKey k where
@@ -615,6 +620,31 @@ parseUnique :: FromHttpApiData v => Text -> Form -> Either Text v
615620parseUnique key form = lookupUnique key form >>= parseQueryParam
616621
617622-- | 'Generic'-based deriving options for 'ToForm' and 'FromForm'.
623+--
624+-- A common use case for non-default 'FormOptions'
625+-- is to strip a prefix off of field labels:
626+--
627+-- @
628+-- data Project = Project
629+-- { projectName :: String
630+-- , projectSize :: Int
631+-- } deriving ('Generic', 'Show')
632+--
633+-- myOptions :: 'FormOptions'
634+-- myOptions = 'FormOptions'
635+-- { 'fieldLabelModifier' = 'map' 'toLower' . 'drop' ('length' \"project\") }
636+--
637+-- instance 'ToForm' Project where
638+-- 'toForm' = 'genericToForm' myOptions
639+--
640+-- instance 'FromForm' Project where
641+-- 'fromForm' = 'genericFromForm' myOptions
642+-- @
643+--
644+-- >>> urlEncodeAsForm Project { projectName = "http-api-data", projectSize = 172 }
645+-- "size=172&name=http-api-data"
646+-- >>> urlDecodeAsForm "name=http-api-data&size=172" :: Either Text Project
647+-- Right (Project {projectName = "http-api-data", projectSize = 172})
618648data FormOptions = FormOptions
619649 { -- | Function applied to field labels. Handy for removing common record prefixes for example.
620650 fieldLabelModifier :: String -> String