@@ -2,9 +2,17 @@
22{-# LANGUAGE FlexibleInstances #-}
33{-# LANGUAGE OverloadedStrings #-}
44{-# LANGUAGE TypeSynonymInstances #-}
5+-- |
6+-- Convert Haskell values to and from HTTP API data
7+-- such as URL pieces, headers and query parameters.
58module Web.HttpApiData (
9+ -- * Examples
10+ -- $examples
11+
12+ -- * Classes
613 ToHttpApiData (..),
714 FromHttpApiData (..),
15+ -- * Utility functions
816 parseMaybeHttpApiData,
917 showUrlPiece,
1018 readMaybeUrlPiece,
@@ -29,6 +37,11 @@ import Data.Time (Day)
2937
3038import Text.Read (readMaybe)
3139
40+-- $setup
41+--
42+-- >>> :set -XOverloadedStrings
43+-- >>> import Data.Time
44+
3245-- | Convert value to HTTP API data.
3346class ToHttpApiData a where
3447 -- | Convert to URL path piece.
@@ -117,3 +130,35 @@ instance FromHttpApiData String where parseUrlPiece = Right . Text.unpack
117130instance FromHttpApiData Text where parseUrlPiece = Right
118131instance FromHttpApiData TL.Text where parseUrlPiece = Right . TL.fromStrict
119132instance FromHttpApiData Day where parseUrlPiece = readEitherUrlPiece
133+
134+-- $examples
135+--
136+-- Booleans:
137+--
138+-- >>> toUrlPiece True
139+-- "True"
140+-- >>> parseUrlPiece "False" :: Either Text Bool
141+-- Right False
142+-- >>> parseUrlPiece "something else" :: Either Text Bool
143+-- Left "could not convert: `something else'"
144+--
145+-- Numbers:
146+--
147+-- >>> toUrlPiece 45.2
148+-- "45.2"
149+-- >>> parseUrlPiece "452" :: Either Text Int
150+-- Right 452
151+--
152+-- Strings:
153+--
154+-- >>> toHeader "hello"
155+-- "hello"
156+-- >>> parseHeader "world" :: Either Text String
157+-- Right "world"
158+--
159+-- Calendar day:
160+--
161+-- >>> toQueryParam (fromGregorian 2015 10 03)
162+-- "2015-10-03"
163+-- >>> toGregorian <$> parseQueryParam "2016-12-01"
164+-- Right (2016,12,1)