git.iko.soy/typeable/http-api-data
on master help sign in
Add two convenience functions for encoding / decoding a ByteString directly to / from a datatype.
6487f48(cdep)illabout
src/Web/HttpApiData/Internal/FormUrlEncoded.hs+16
@@ -291,3 +291,19 @@ decodeForm q = do
291 toForm <$> mapM parsePair xs
291 toForm <$> mapM parsePair xs
292
292
293data Proxy3 a b c = Proxy3
293data Proxy3 a b c = Proxy3
294+
295+-- | This is a convenience function for decoding a
296+-- @application/x-www-form-urlencoded@ 'BSL.ByteString' directly to a datatype
297+-- that has an instance for 'FromForm'.
298+--
299+-- This is effectively @'fromForm' '<=<' 'decodeForm'@.
300+decodeWithFromForm :: (FromForm a) => BSL.ByteString -> Either T.Text a
301+decodeWithFromForm = fromForm <=< decodeForm
302+
303+-- | This is a convenience function for encoding a datatype that has instance
304+-- for 'ToForm' directly to a @application/x-www-form-urlencoded@
305+-- 'BSL.ByteString'.
306+--
307+-- This is effectively @'encodeForm' . 'toForm'@.
308+encodeWithToForm :: (ToForm a) => a -> BSL.ByteString
309+encodeWithToForm = encodeForm . toForm
test/Web/HttpApiData/Internal/FormUrlEncodedSpec.hs+8
@@ -7,6 +7,8 @@ module Web.HttpApiData.Internal.FormUrlEncodedSpec (spec) where
7import Control.Applicative
7import Control.Applicative
8#endif
8#endif
9
9
10+import Control.Monad ((<=<))
11+import qualified Data.ByteString.Lazy.Char8 as BSL
10import qualified Data.Map as M
12import qualified Data.Map as M
11import Data.Text (Text, unpack)
13import Data.Text (Text, unpack)
12import Test.Hspec
14import Test.Hspec
@@ -74,3 +76,9 @@ urlEncoding = describe "urlEncoding" $ do
74
76
75 it "decodeForm (encodeForm x) == Right x" $ property $ \(NoEmptyKeyForm x) -> do
77 it "decodeForm (encodeForm x) == Right x" $ property $ \(NoEmptyKeyForm x) -> do
76 decodeForm (encodeForm x) `shouldBe` Right x
78 decodeForm (encodeForm x) `shouldBe` Right x
79+
80+ it "decodeWithFromForm == (fromForm <=< decodeForm)" $ property $ \(x :: BSL.ByteString) -> do
81+ (decodeWithFromForm x :: Either Text Form) `shouldBe` (fromForm <=< decodeForm) x
82+
83+ it "encodeWithToForm == encodeForm . toForm" $ property $ \(x :: Form) -> do
84+ encodeWithToForm x `shouldBe` (encodeForm . toForm) x