git.iko.soy/typeable/http-api-data
on master help sign in
Add usage examples for HttpApiData helpers
commit09e52f85e59db949764977a93b4a470288ef6876 authorNickolay Kudasov <nickolay.kudasov@gmail.com> dateWed 7 Oct 2015, 13:04 (11 years ago) parentac654a4
1 file changed+25
Web/HttpApiData/Internal.hs+25
Web/HttpApiData/Internal.hs+25
@@ -76,6 +76,17 @@ parseMaybeTextData parse input =
7676 Just val -> Right val
7777
7878-- | Convert to URL piece using @'Show'@ instance.
79+-- The result is always lower cased.
80+--
81+-- >>> showTextData True
82+-- "true"
83+--
84+-- This can be used as a default implementation for enumeration types:
85+--
86+-- >>> data MyData = Foo | Bar | Baz deriving (Show)
87+-- >>> instance ToHttpApiData MyData where toUrlPiece = showTextData
88+-- >>> toUrlPiece Foo
89+-- "foo"
7990showTextData :: Show a => a -> Text
8091showTextData = T.toLower . T.pack . show
8192
@@ -85,6 +96,13 @@ showTextData = T.toLower . T.pack . show
8596-- Right 10
8697-- >>> parseUrlPieceWithPrefix "Left " "left" :: Either Text Bool
8798-- Left "could not convert: `left'"
99+--
100+-- This can be used to implement @'FromHttpApiData'@ for single field constructors:
101+--
102+-- >>> data Foo = Foo Int deriving (Show)
103+-- >>> instance FromHttpApiData Foo where parseUrlPiece s = Foo <$> parseUrlPieceWithPrefix "Foo " s
104+-- >>> parseUrlPiece "foo 1" :: Either Text Foo
105+-- Right (Foo 1)
88106parseUrlPieceWithPrefix :: FromHttpApiData a => Text -> Text -> Either Text a
89107parseUrlPieceWithPrefix pattern input
90108 | T.toLower pattern == T.toLower prefix = parseUrlPiece rest
@@ -98,6 +116,13 @@ parseUrlPieceWithPrefix pattern input
98116-- Right True
99117-- >>> parseBoundedCaseInsensitiveTextData "FALSE" :: Either Text Bool
100118-- Right False
119+--
120+-- This can be used as a default implementation for enumeration types:
121+--
122+-- >>> data MyData = Foo | Bar | Baz deriving (Show, Bounded, Enum)
123+-- >>> instance FromHttpApiData MyData where parseUrlPiece = parseBoundedCaseInsensitiveTextData
124+-- >>> parseUrlPiece "foo" :: Either Text MyData
125+-- Right Foo
101126parseBoundedCaseInsensitiveTextData :: forall a. (Show a, Bounded a, Enum a) => Text -> Either Text a
102127parseBoundedCaseInsensitiveTextData = parseMaybeTextData (flip lookup values . T.toLower)
103128 where