git.iko.soy/typeable/http-api-data
on master help sign in
Add parse*WithPrefix helpers
commit586373163021ae0138289f704e5e96ba97d96f7f authorNickolay Kudasov <nickolay.kudasov@gmail.com> dateSun 11 Oct 2015, 13:15 (11 years ago) parent7bd77b3
2 files changed+39−3
Web/HttpApiData.hs+6−2 Web/HttpApiData/Internal.hs+33−1
Web/HttpApiData.hs+6−2
@@ -14,11 +14,15 @@ module Web.HttpApiData (
1414 parseHeaderMaybe,
1515 parseQueryParamMaybe,
1616
17− -- * Helpers
17+ -- * Prefix parsers
18+ parseUrlPieceWithPrefix,
19+ parseHeaderWithPrefix,
20+ parseQueryParamWithPrefix,
21+
22+ -- * Other helpers
1823 showTextData,
1924 readTextData,
2025 parseBoundedTextData,
21− parseUrlPieceWithPrefix,
2226) where
2327
2428import Web.HttpApiData.Internal
Web/HttpApiData/Internal.hs+33−1
@@ -16,6 +16,7 @@ import Control.Arrow ((&&&))
1616
1717import Data.Monoid
1818import Data.ByteString (ByteString)
19+import qualified Data.ByteString as BS
1920
2021import Data.Int
2122import Data.Word
@@ -149,7 +150,8 @@ showt = T.pack . show
149150
150151-- | /Case insensitive/.
151152--
152−-- Parse given text case insensitive and return the rest of the input.
153+-- Parse given text case insensitive and then parse the rest of the input
154+-- using @'parseUrlPiece'@.
153155--
154156-- >>> parseUrlPieceWithPrefix "Just " "just 10" :: Either Text Int
155157-- Right 10
@@ -169,6 +171,36 @@ parseUrlPieceWithPrefix pattern input
169171 where
170172 (prefix, rest) = T.splitAt (T.length pattern) input
171173
174+-- | Parse given bytestring then parse the rest of the input using @'parseHeader'@.
175+--
176+-- >>> :{
177+-- newtype BasicAuthToken = BasicAuthToken Text deriving (Show)
178+-- instance FromHttpApiData BasicAuthToken where
179+-- parseHeader h = BasicAuthToken <$> parseHeaderWithPrefix "Basic " h
180+-- parseQueryParam p = BasicAuthToken <$> parseQueryParam p
181+-- :}
182+--
183+-- >>> parseHeader "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" :: Either Text BasicAuthToken
184+-- Right (BasicAuthToken "QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
185+parseHeaderWithPrefix :: FromHttpApiData a => ByteString -> ByteString -> Either Text a
186+parseHeaderWithPrefix pattern input
187+ | pattern `BS.isPrefixOf` input = parseHeader (BS.drop (BS.length pattern) input)
188+ | otherwise = defaultParseError (showt input)
189+
190+-- | /Case insensitive/.
191+--
192+-- Parse given text case insensitive and then parse the rest of the input
193+-- using @'parseQueryParam'@.
194+--
195+-- >>> parseQueryParamWithPrefix "z" "z10" :: Either Text Int
196+-- Right 10
197+parseQueryParamWithPrefix :: FromHttpApiData a => Text -> Text -> Either Text a
198+parseQueryParamWithPrefix pattern input
199+ | T.toLower pattern == T.toLower prefix = parseQueryParam rest
200+ | otherwise = defaultParseError input
201+ where
202+ (prefix, rest) = T.splitAt (T.length pattern) input
203+
172204#if USE_TEXT_SHOW
173205-- | /Case insensitive/.
174206--