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.
commit6487f489340b7a1c913a0d3850a663705fbc79b0 author(cdep)illabout <cdep.illabout@gmail.com> dateFri 26 Aug 2016, 22:00 (10 years ago) parent8ab1a1f
2 files changed+24
src/Web/HttpApiData/Internal/FormUrlEncoded.hs+16 test/Web/HttpApiData/Internal/FormUrlEncodedSpec.hs+8
src/Web/HttpApiData/Internal/FormUrlEncoded.hs+16
@@ -291,3 +291,19 @@ decodeForm q = do
291291 toForm <$> mapM parsePair xs
292292
293293data 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
77import Control.Applicative
88#endif
99
10+import Control.Monad ((<=<))
11+import qualified Data.ByteString.Lazy.Char8 as BSL
1012import qualified Data.Map as M
1113import Data.Text (Text, unpack)
1214import Test.Hspec
@@ -74,3 +76,9 @@ urlEncoding = describe "urlEncoding" $ do
7476
7577 it "decodeForm (encodeForm x) == Right x" $ property $ \(NoEmptyKeyForm x) -> do
7678 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