git.iko.soy/typeable/http-api-data
on master help sign in
Add usage examples for HttpApiData helpers
09e52f8Nickolay Kudasov
Web/HttpApiData/Internal.hs+25
@@ -76,6 +76,17 @@ parseMaybeTextData parse input =
76 Just val -> Right val
76 Just val -> Right val
77
77
78-- | Convert to URL piece using @'Show'@ instance.
78-- | 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"
79showTextData :: Show a => a -> Text
90showTextData :: Show a => a -> Text
80showTextData = T.toLower . T.pack . show
91showTextData = T.toLower . T.pack . show
81
92
@@ -85,6 +96,13 @@ showTextData = T.toLower . T.pack . show
85-- Right 10
96-- Right 10
86-- >>> parseUrlPieceWithPrefix "Left " "left" :: Either Text Bool
97-- >>> parseUrlPieceWithPrefix "Left " "left" :: Either Text Bool
87-- Left "could not convert: `left'"
98-- 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)
88parseUrlPieceWithPrefix :: FromHttpApiData a => Text -> Text -> Either Text a
106parseUrlPieceWithPrefix :: FromHttpApiData a => Text -> Text -> Either Text a
89parseUrlPieceWithPrefix pattern input
107parseUrlPieceWithPrefix pattern input
90 | T.toLower pattern == T.toLower prefix = parseUrlPiece rest
108 | T.toLower pattern == T.toLower prefix = parseUrlPiece rest
@@ -98,6 +116,13 @@ parseUrlPieceWithPrefix pattern input
98-- Right True
116-- Right True
99-- >>> parseBoundedCaseInsensitiveTextData "FALSE" :: Either Text Bool
117-- >>> parseBoundedCaseInsensitiveTextData "FALSE" :: Either Text Bool
100-- Right False
118-- 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
101parseBoundedCaseInsensitiveTextData :: forall a. (Show a, Bounded a, Enum a) => Text -> Either Text a
126parseBoundedCaseInsensitiveTextData :: forall a. (Show a, Bounded a, Enum a) => Text -> Either Text a
102parseBoundedCaseInsensitiveTextData = parseMaybeTextData (flip lookup values . T.toLower)
127parseBoundedCaseInsensitiveTextData = parseMaybeTextData (flip lookup values . T.toLower)
103 where
128 where