@@ -1,4 +1,3 @@
1−{-# LANGUAGE ConstraintKinds #-}
2{-# LANGUAGE CPP #-}
1{-# LANGUAGE CPP #-}
3{-# LANGUAGE DataKinds #-}
2{-# LANGUAGE DataKinds #-}
4{-# LANGUAGE DefaultSignatures #-}
3{-# LANGUAGE DefaultSignatures #-}
@@ -14,54 +13,56 @@
14{-# LANGUAGE TypeFamilies #-}
13{-# LANGUAGE TypeFamilies #-}
15{-# LANGUAGE TypeOperators #-}
14{-# LANGUAGE TypeOperators #-}
16{-# LANGUAGE UndecidableInstances #-}
15{-# LANGUAGE UndecidableInstances #-}
17−#include "overlapping-compat.h"
18module Web.Internal.FormUrlEncoded where
16module Web.Internal.FormUrlEncoded where
20−import Prelude ()
18+#if __GLASGOW_HASKELL__ < 710
21−import Prelude.Compat
19+import Control.Applicative
20+import Data.Traversable
23+#if __GLASGOW_HASKELL__ < 800
24+import GHC.Exts (IsList (..))
26+import GHC.Exts (IsList (..), Constraint)
23−import Control.Applicative (Const(Const))
24import Control.Arrow ((***))
30import Control.Arrow ((***))
25import Control.Monad ((<=<))
31import Control.Monad ((<=<))
26−import Data.ByteString.Builder (shortByteString, toLazyByteString)
32+import Data.ByteString.Builder (toLazyByteString, shortByteString)
27import qualified Data.ByteString.Lazy as BSL
33import qualified Data.ByteString.Lazy as BSL
28import qualified Data.ByteString.Lazy.Char8 as BSL8
34import qualified Data.ByteString.Lazy.Char8 as BSL8
29−import Data.Coerce (coerce)
30import qualified Data.Foldable as F
35import qualified Data.Foldable as F
31−import Data.Functor.Identity (Identity(Identity))
32import Data.Hashable (Hashable)
36import Data.Hashable (Hashable)
33import Data.HashMap.Strict (HashMap)
37import Data.HashMap.Strict (HashMap)
34import qualified Data.HashMap.Strict as HashMap
38import qualified Data.HashMap.Strict as HashMap
35−import Data.Int (Int16, Int32, Int64, Int8)
39+import Data.Int
36import Data.IntMap (IntMap)
40import Data.IntMap (IntMap)
37import qualified Data.IntMap as IntMap
41import qualified Data.IntMap as IntMap
38−import Data.List (intersperse, sortBy)
42+import Data.List (intersperse)
39import Data.Map (Map)
43import Data.Map (Map)
40import qualified Data.Map as Map
44import qualified Data.Map as Map
41−import Data.Monoid (All (..), Any (..), Dual (..),
45+import Data.Monoid
42− Product (..), Sum (..))
46+
43−import Data.Ord (comparing)
44−import Data.Proxy (Proxy (..))
45−import Data.Semigroup (Semigroup (..))
46−import qualified Data.Semigroup as Semi
47−import Data.Tagged (Tagged (..))
48import Data.Text (Text)
47import Data.Text (Text)
49import qualified Data.Text as Text
48import qualified Data.Text as Text
50−import qualified Data.Text.Encoding as Text
51−import Data.Text.Encoding.Error (lenientDecode)
52import qualified Data.Text.Lazy as Lazy
49import qualified Data.Text.Lazy as Lazy
53−import Data.Time.Compat (Day, LocalTime, NominalDiffTime,
50+import Data.Text.Encoding as Text
54− UTCTime, ZonedTime)
51+import Data.Text.Encoding.Error (lenientDecode)
55−import Data.Time.Calendar.Month.Compat (Month)
52+
56−import Data.Time.Calendar.Quarter.Compat (Quarter, QuarterOfYear (..))
53+import Data.Time
57−import Data.Void (Void)
54+import Data.Proxy
58−import Data.Word (Word16, Word32, Word64, Word8)
55+import Data.Word
59−import GHC.Exts (Constraint, IsList (..))
56+
57+#if MIN_VERSION_base(4,8,0)
59+import Numeric.Natural
60import GHC.Generics
62import GHC.Generics
61−import GHC.TypeLits
63+import URI.ByteString (urlEncodeQuery, urlDecodeQuery)
62−import Network.HTTP.Types.URI (urlDecode, urlEncodeBuilder)
64+
63−import Numeric.Natural (Natural)
64−import Web.Internal.HttpApiData
65+import Web.Internal.HttpApiData
67-- >>> :set -XDeriveGeneric
68-- >>> :set -XDeriveGeneric
@@ -70,20 +71,11 @@ import Web.Internal.HttpApiData
70-- >>> :set -XFlexibleContexts
71-- >>> :set -XFlexibleContexts
71-- >>> :set -XScopedTypeVariables
72-- >>> :set -XScopedTypeVariables
72-- >>> :set -XTypeFamilies
73-- >>> :set -XTypeFamilies
73−-- >>> import Data.Char (toLower)
74+-- >>> import Data.Either (isLeft)
74−--
75+-- >>> import Data.List (sort)
75-- >>> data Person = Person { name :: String, age :: Int } deriving (Show, Generic)
76-- >>> data Person = Person { name :: String, age :: Int } deriving (Show, Generic)
76-- >>> instance ToForm Person
77-- >>> instance ToForm Person
77-- >>> instance FromForm Person
78-- >>> instance FromForm Person
79−-- >>> data Post = Post { title :: String, subtitle :: Maybe String, comments :: [String]} deriving (Generic, Show)
80−-- >>> instance ToForm Post
81−-- >>> instance FromForm Post
83−-- >>> data Project = Project { projectName :: String, projectSize :: Int } deriving (Generic, Show)
84−-- >>> let myOptions = FormOptions { fieldLabelModifier = map toLower . drop (length ("project" :: String)) }
85−-- >>> instance ToForm Project where toForm = genericToForm myOptions
86−-- >>> instance FromForm Project where fromForm = genericFromForm myOptions
88-- | Typeclass for types that can be used as keys in a 'Form'-like container (like 'Map').
80-- | Typeclass for types that can be used as keys in a 'Form'-like container (like 'Map').
89class ToFormKey k where
81class ToFormKey k where
@@ -115,9 +107,6 @@ instance ToFormKey LocalTime where toFormKey = toQueryParam
115instance ToFormKey ZonedTime where toFormKey = toQueryParam
107instance ToFormKey ZonedTime where toFormKey = toQueryParam
116instance ToFormKey UTCTime where toFormKey = toQueryParam
108instance ToFormKey UTCTime where toFormKey = toQueryParam
117instance ToFormKey NominalDiffTime where toFormKey = toQueryParam
109instance ToFormKey NominalDiffTime where toFormKey = toQueryParam
118−instance ToFormKey Quarter where toFormKey = toQueryParam
119−instance ToFormKey QuarterOfYear where toFormKey = toQueryParam
120−instance ToFormKey Month where toFormKey = toQueryParam
122instance ToFormKey String where toFormKey = toQueryParam
111instance ToFormKey String where toFormKey = toQueryParam
123instance ToFormKey Text where toFormKey = toQueryParam
112instance ToFormKey Text where toFormKey = toQueryParam
@@ -126,26 +115,14 @@ instance ToFormKey Lazy.Text where toFormKey = toQueryParam
126instance ToFormKey All where toFormKey = toQueryParam
115instance ToFormKey All where toFormKey = toQueryParam
127instance ToFormKey Any where toFormKey = toQueryParam
116instance ToFormKey Any where toFormKey = toQueryParam
129−instance ToFormKey a => ToFormKey (Dual a) where toFormKey = coerce (toFormKey :: a -> Text)
118+instance ToFormKey a => ToFormKey (Dual a) where toFormKey = toFormKey . getDual
130−instance ToFormKey a => ToFormKey (Sum a) where toFormKey = coerce (toFormKey :: a -> Text)
119+instance ToFormKey a => ToFormKey (Sum a) where toFormKey = toFormKey . getSum
131−instance ToFormKey a => ToFormKey (Product a) where toFormKey = coerce (toFormKey :: a -> Text)
120+instance ToFormKey a => ToFormKey (Product a) where toFormKey = toFormKey . getProduct
133−instance ToFormKey a => ToFormKey (Semi.Min a) where toFormKey = coerce (toFormKey :: a -> Text)
134−instance ToFormKey a => ToFormKey (Semi.Max a) where toFormKey = coerce (toFormKey :: a -> Text)
135−instance ToFormKey a => ToFormKey (Semi.First a) where toFormKey = coerce (toFormKey :: a -> Text)
136−instance ToFormKey a => ToFormKey (Semi.Last a) where toFormKey = coerce (toFormKey :: a -> Text)
138−instance ToFormKey a => ToFormKey (Tagged b a) where toFormKey = coerce (toFormKey :: a -> Text)
141−instance ToFormKey a => ToFormKey (Identity a) where toFormKey = coerce (toFormKey :: a -> Text)
144−instance ToFormKey a => ToFormKey (Const a b) where
145− toFormKey = coerce (toFormKey :: a -> Text)
122+#if MIN_VERSION_base(4,8,0)
147instance ToFormKey Void where toFormKey = toQueryParam
123instance ToFormKey Void where toFormKey = toQueryParam
148instance ToFormKey Natural where toFormKey = toQueryParam
124instance ToFormKey Natural where toFormKey = toQueryParam
150-- | Typeclass for types that can be parsed from keys of a 'Form'. This is the reverse of 'ToFormKey'.
127-- | Typeclass for types that can be parsed from keys of a 'Form'. This is the reverse of 'ToFormKey'.
151class FromFormKey k where
128class FromFormKey k where
@@ -177,9 +154,6 @@ instance FromFormKey LocalTime where parseFormKey = parseQueryParam
177instance FromFormKey ZonedTime where parseFormKey = parseQueryParam
154instance FromFormKey ZonedTime where parseFormKey = parseQueryParam
178instance FromFormKey UTCTime where parseFormKey = parseQueryParam
155instance FromFormKey UTCTime where parseFormKey = parseQueryParam
179instance FromFormKey NominalDiffTime where parseFormKey = parseQueryParam
156instance FromFormKey NominalDiffTime where parseFormKey = parseQueryParam
180−instance FromFormKey Quarter where parseFormKey = parseQueryParam
181−instance FromFormKey QuarterOfYear where parseFormKey = parseQueryParam
182−instance FromFormKey Month where parseFormKey = parseQueryParam
184instance FromFormKey String where parseFormKey = parseQueryParam
158instance FromFormKey String where parseFormKey = parseQueryParam
185instance FromFormKey Text where parseFormKey = parseQueryParam
159instance FromFormKey Text where parseFormKey = parseQueryParam
@@ -188,48 +162,30 @@ instance FromFormKey Lazy.Text where parseFormKey = parseQueryParam
188instance FromFormKey All where parseFormKey = parseQueryParam
162instance FromFormKey All where parseFormKey = parseQueryParam
189instance FromFormKey Any where parseFormKey = parseQueryParam
163instance FromFormKey Any where parseFormKey = parseQueryParam
191−instance FromFormKey a => FromFormKey (Dual a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
165+instance FromFormKey a => FromFormKey (Dual a) where parseFormKey = fmap Dual . parseFormKey
192−instance FromFormKey a => FromFormKey (Sum a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
166+instance FromFormKey a => FromFormKey (Sum a) where parseFormKey = fmap Sum . parseFormKey
193−instance FromFormKey a => FromFormKey (Product a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
195−instance FromFormKey a => FromFormKey (Semi.Min a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
196−instance FromFormKey a => FromFormKey (Semi.Max a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
197−instance FromFormKey a => FromFormKey (Semi.First a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
198−instance FromFormKey a => FromFormKey (Semi.Last a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
200−instance FromFormKey a => FromFormKey (Tagged b a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
167+instance FromFormKey a => FromFormKey (Product a) where parseFormKey = fmap Product . parseFormKey
203−instance FromFormKey a => FromFormKey (Identity a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
206−instance FromFormKey a => FromFormKey (Const a b) where
207− parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
169+#if MIN_VERSION_base(4,8,0)
209instance FromFormKey Void where parseFormKey = parseQueryParam
170instance FromFormKey Void where parseFormKey = parseQueryParam
210instance FromFormKey Natural where parseFormKey = parseQueryParam
171instance FromFormKey Natural where parseFormKey = parseQueryParam
212-- | The contents of a form, not yet URL-encoded.
174-- | The contents of a form, not yet URL-encoded.
214-- 'Form' can be URL-encoded with 'urlEncodeForm' and URL-decoded with 'urlDecodeForm'.
176-- 'Form' can be URL-encoded with 'urlEncodeForm' and URL-decoded with 'urlDecodeForm'.
215newtype Form = Form { unForm :: HashMap Text [Text] }
177newtype Form = Form { unForm :: HashMap Text [Text] }
216− deriving (Eq, Read, Generic, Semigroup, Monoid)
178+ deriving (Eq, Read, Generic, Monoid)
218instance Show Form where
180instance Show Form where
219 showsPrec d form = showParen (d > 10) $
181 showsPrec d form = showParen (d > 10) $
220− showString "fromList " . shows (toListStable form)
182+ showString "fromList " . shows (toList form)
222−-- | _NOTE:_ 'toList' is unstable and may result in different key order (but not values).
223−-- For a stable conversion use 'toListStable'.
224instance IsList Form where
184instance IsList Form where
225 type Item Form = (Text, Text)
185 type Item Form = (Text, Text)
226 fromList = Form . HashMap.fromListWith (flip (<>)) . fmap (\(k, v) -> (k, [v]))
186 fromList = Form . HashMap.fromListWith (flip (<>)) . fmap (\(k, v) -> (k, [v]))
227 toList = concatMap (\(k, vs) -> map ((,) k) vs) . HashMap.toList . unForm
187 toList = concatMap (\(k, vs) -> map ((,) k) vs) . HashMap.toList . unForm
229−-- | A stable version of 'toList'.
230−toListStable :: Form -> [(Text, Text)]
231−toListStable = sortOn fst . toList
233-- | Convert a value into 'Form'.
189-- | Convert a value into 'Form'.
235-- An example type and instance:
191-- An example type and instance:
@@ -266,6 +222,7 @@ toListStable = sortOn fst . toList
268-- The default implementation of 'toForm' is 'genericToForm'.
224-- The default implementation of 'toForm' is 'genericToForm'.
225+-- It only works for records and it will use 'toQueryParam' for each field's value.
269class ToForm a where
226class ToForm a where
270 -- | Convert a value into 'Form'.
227 -- | Convert a value into 'Form'.
271 toForm :: a -> Form
228 toForm :: a -> Form
@@ -297,8 +254,6 @@ data Proxy3 a b c = Proxy3
298type family NotSupported (cls :: k1) (a :: k2) (reason :: Symbol) :: Constraint where
255type family NotSupported (cls :: k1) (a :: k2) (reason :: Symbol) :: Constraint where
299#if __GLASGOW_HASKELL__ < 800
256#if __GLASGOW_HASKELL__ < 800
300− -- this is just a placeholder case for older GHCs to not freak out on an empty closed type family
301− NotSupported cls a "this type family is actually empty" = ()
303 NotSupported cls a reason = TypeError
258 NotSupported cls a reason = TypeError
304 ( 'Text "Cannot derive a Generic-based " ':<>: 'ShowType cls ':<>: 'Text " instance for " ':<>: 'ShowType a ':<>: 'Text "." ':$$:
259 ( 'Text "Cannot derive a Generic-based " ':<>: 'ShowType cls ':<>: 'Text " instance for " ':<>: 'ShowType a ':<>: 'Text "." ':$$:
@@ -318,30 +273,6 @@ type family NotSupported (cls :: k1) (a :: k2) (reason :: Symbol) :: Constraint
318-- , age :: Int
273-- , age :: Int
319-- } deriving ('Generic')
274-- } deriving ('Generic')
322−-- In this implementation each field's value gets encoded using `toQueryParam`.
323−-- Two field types are exceptions:
325−-- - for values of type @'Maybe' a@ an entry is added to the 'Form' only when it is @'Just' x@
326−-- and the encoded value is @'toQueryParam' x@; 'Nothing' values are omitted from the 'Form';
328−-- - for values of type @[a]@ (except @['Char']@) an entry is added for every item in the list;
329−-- if the list is empty no entries are added to the 'Form';
331−-- Here's an example:
336−-- , subtitle :: Maybe String
337−-- , comments :: [String]
338−-- } deriving ('Generic', 'Show')
340−-- instance 'ToForm' Post
343−-- >>> urlEncodeAsFormStable Post { title = "Test", subtitle = Nothing, comments = ["Nice post!", "+1"] }
344−-- "comments=Nice%20post%21&comments=%2B1&title=Test"
345genericToForm :: forall a. (Generic a, GToForm a (Rep a)) => FormOptions -> a -> Form
276genericToForm :: forall a. (Generic a, GToForm a (Rep a)) => FormOptions -> a -> Form
346genericToForm opts = gToForm (Proxy :: Proxy a) opts . from
277genericToForm opts = gToForm (Proxy :: Proxy a) opts . from
@@ -357,25 +288,7 @@ instance (GToForm t f) => GToForm t (M1 D x f) where
357instance (GToForm t f) => GToForm t (M1 C x f) where
288instance (GToForm t f) => GToForm t (M1 C x f) where
358 gToForm p opts (M1 a) = gToForm p opts a
289 gToForm p opts (M1 a) = gToForm p opts a
360−instance OVERLAPPABLE_ (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i c)) where
361− gToForm _ opts (M1 (K1 c)) = fromList [(key, toQueryParam c)]
363− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
365−instance (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i (Maybe c))) where
291+instance (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i c)) where
366− gToForm _ opts (M1 (K1 c)) =
369− Just x -> fromList [(key, toQueryParam x)]
371− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
373−instance (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i [c])) where
374− gToForm _ opts (M1 (K1 cs)) = fromList (map (\c -> (key, toQueryParam c)) cs)
376− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
378−instance OVERLAPPING_ (Selector s) => GToForm t (M1 S s (K1 i String)) where
379 gToForm _ opts (M1 (K1 c)) = fromList [(key, toQueryParam c)]
292 gToForm _ opts (M1 (K1 c)) = fromList [(key, toQueryParam c)]
381 key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
294 key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
@@ -392,9 +305,9 @@ instance NotSupported ToForm t "is a sum type" => GToForm t (f :+: g) where gToF
392-- , age :: Int }
305-- , age :: Int }
394-- instance 'FromForm' Person where
307-- instance 'FromForm' Person where
395−-- 'fromForm' f = Person
308+-- 'fromForm' (Form m) = Person
396−-- '<$>' 'parseUnique' "name" f
309+-- '<$>' 'parseUnique' "name" m
397−-- '<*>' 'parseUnique' "age" f
310+-- '<*>' 'parseUnique' "age" m
400-- Instead of manually writing @'FromForm'@ instances you can
313-- Instead of manually writing @'FromForm'@ instances you can
@@ -425,7 +338,6 @@ class FromForm a where
426instance FromForm Form where fromForm = pure
339instance FromForm Form where fromForm = pure
428−-- | _NOTE:_ this conversion is unstable and may result in different key order (but not values).
429instance (FromFormKey k, FromHttpApiData v) => FromForm [(k, v)] where
341instance (FromFormKey k, FromHttpApiData v) => FromForm [(k, v)] where
430 fromForm = fmap (concatMap (\(k, vs) -> map ((,) k) vs)) . toEntriesByKey
342 fromForm = fmap (concatMap (\(k, vs) -> map ((,) k) vs)) . toEntriesByKey
@@ -440,22 +352,13 @@ instance FromHttpApiData v => FromForm (IntMap [v]) where
441-- | Parse a 'Form' into a list of entries groupped by key.
353-- | Parse a 'Form' into a list of entries groupped by key.
443−-- _NOTE:_ this conversion is unstable and may result in different key order
355+-- >>> toEntriesByKey [("name", "Nick"), ("color", "red"), ("color", "white")] :: Either Text [(Text, [Text])]
444−-- (but not values). For a stable encoding see 'toEntriesByKeyStable'.
356+-- Right [("color",["red","white"]),("name",["Nick"])]
445toEntriesByKey :: (FromFormKey k, FromHttpApiData v) => Form -> Either Text [(k, [v])]
357toEntriesByKey :: (FromFormKey k, FromHttpApiData v) => Form -> Either Text [(k, [v])]
446toEntriesByKey = traverse parseGroup . HashMap.toList . unForm
358toEntriesByKey = traverse parseGroup . HashMap.toList . unForm
448 parseGroup (k, vs) = (,) <$> parseFormKey k <*> traverse parseQueryParam vs
360 parseGroup (k, vs) = (,) <$> parseFormKey k <*> traverse parseQueryParam vs
450−-- | Parse a 'Form' into a list of entries groupped by key.
452−-- >>> toEntriesByKeyStable [("name", "Nick"), ("color", "red"), ("color", "white")] :: Either Text [(Text, [Text])]
453−-- Right [("color",["red","white"]),("name",["Nick"])]
455−-- For an unstable (but faster) conversion see 'toEntriesByKey'.
456−toEntriesByKeyStable :: (Ord k, FromFormKey k, FromHttpApiData v) => Form -> Either Text [(k, [v])]
457−toEntriesByKeyStable = fmap (sortOn fst) . toEntriesByKey
459-- | A 'Generic'-based implementation of 'fromForm'.
362-- | A 'Generic'-based implementation of 'fromForm'.
460-- This is used as a default implementation in 'FromForm'.
363-- This is used as a default implementation in 'FromForm'.
@@ -467,29 +370,6 @@ toEntriesByKeyStable = fmap (sortOn fst) . toEntriesByKey
467-- , age :: Int
370-- , age :: Int
468-- } deriving ('Generic')
371-- } deriving ('Generic')
471−-- In this implementation each field's value gets decoded using `parseQueryParam`.
472−-- Two field types are exceptions:
474−-- - for values of type @'Maybe' a@ an entry is parsed if present in the 'Form'
475−-- and the is decoded with 'parseQueryParam'; if no entry is present result is 'Nothing';
477−-- - for values of type @[a]@ (except @['Char']@) all entries are parsed to produce a list of parsed values;
479−-- Here's an example:
484−-- , subtitle :: Maybe String
485−-- , comments :: [String]
486−-- } deriving ('Generic', 'Show')
488−-- instance 'FromForm' Post
491−-- >>> urlDecodeAsForm "comments=Nice%20post%21&comments=%2B1&title=Test" :: Either Text Post
492−-- Right (Post {title = "Test", subtitle = Nothing, comments = ["Nice post!","+1"]})
493genericFromForm :: forall a. (Generic a, GFromForm a (Rep a)) => FormOptions -> Form -> Either Text a
373genericFromForm :: forall a. (Generic a, GFromForm a (Rep a)) => FormOptions -> Form -> Either Text a
494genericFromForm opts f = to <$> gFromForm (Proxy :: Proxy a) opts f
374genericFromForm opts f = to <$> gFromForm (Proxy :: Proxy a) opts f
@@ -499,83 +379,54 @@ class GFromForm t (f :: * -> *) where
499instance (GFromForm t f, GFromForm t g) => GFromForm t (f :*: g) where
379instance (GFromForm t f, GFromForm t g) => GFromForm t (f :*: g) where
500 gFromForm p opts f = (:*:) <$> gFromForm p opts f <*> gFromForm p opts f
380 gFromForm p opts f = (:*:) <$> gFromForm p opts f <*> gFromForm p opts f
502−instance GFromForm t f => GFromForm t (M1 D x f) where
503− gFromForm p opts f = M1 <$> gFromForm p opts f
505−instance GFromForm t f => GFromForm t (M1 C x f) where
506− gFromForm p opts f = M1 <$> gFromForm p opts f
508−instance OVERLAPPABLE_ (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i c)) where
382+instance (Selector s, FromHttpApiData f) => GFromForm t (M1 S s (K1 i f)) where
509 gFromForm _ opts form = M1 . K1 <$> parseUnique key form
383 gFromForm _ opts form = M1 . K1 <$> parseUnique key form
511 key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
385 key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
513−instance (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i (Maybe c))) where
387+instance GFromForm t f => GFromForm t (M1 D x f) where
514− gFromForm _ opts form = M1 . K1 <$> parseMaybe key form
516− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
518−instance (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i [c])) where
519− gFromForm _ opts form = M1 . K1 <$> parseAll key form
388+ gFromForm p opts f = M1 <$> gFromForm p opts f
521− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
523−instance OVERLAPPING_ (Selector s) => GFromForm t (M1 S s (K1 i String)) where
390+instance GFromForm t f => GFromForm t (M1 C x f) where
524− gFromForm _ opts form = M1 . K1 <$> parseUnique key form
391+ gFromForm p opts f = M1 <$> gFromForm p opts f
526− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
528instance NotSupported FromForm t "is a sum type" => GFromForm t (f :+: g) where gFromForm = error "impossible"
393instance NotSupported FromForm t "is a sum type" => GFromForm t (f :+: g) where gFromForm = error "impossible"
530-- | Encode a 'Form' to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
395-- | Encode a 'Form' to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
532−-- _NOTE:_ this encoding is unstable and may result in different key order
533−-- (but not values). For a stable encoding see 'urlEncodeFormStable'.
534−urlEncodeForm :: Form -> BSL.ByteString
535−urlEncodeForm = urlEncodeParams . toList
537−-- | Encode a 'Form' to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
539−-- For an unstable (but faster) encoding see 'urlEncodeForm'.
541-- Key-value pairs get encoded to @key=value@ and separated by @&@:
397-- Key-value pairs get encoded to @key=value@ and separated by @&@:
543−-- >>> urlEncodeFormStable [("name", "Julian"), ("lastname", "Arni")]
399+-- >>> urlEncodeForm [("name", "Julian"), ("lastname", "Arni")]
544-- "lastname=Arni&name=Julian"
400-- "lastname=Arni&name=Julian"
546-- Keys with empty values get encoded to just @key@ (without the @=@ sign):
402-- Keys with empty values get encoded to just @key@ (without the @=@ sign):
548−-- >>> urlEncodeFormStable [("is_test", "")]
404+-- >>> urlEncodeForm [("is_test", "")]
549-- "is_test"
405-- "is_test"
551-- Empty keys are allowed too:
407-- Empty keys are allowed too:
553−-- >>> urlEncodeFormStable [("", "foobar")]
409+-- >>> urlEncodeForm [("", "foobar")]
554-- "=foobar"
410-- "=foobar"
556−-- However, if both key and value are empty, the key-value pair is ignored.
412+-- However, if not key and value are empty, the key-value pair is ignored.
557−-- (This prevents @'urlDecodeForm' . 'urlEncodeFormStable'@ from being a true isomorphism).
413+-- (This prevents @'urlDecodeForm' . 'urlEncodeForm'@ from being a true isomorphism).
559−-- >>> urlEncodeFormStable [("", "")]
415+-- >>> urlEncodeForm [("", "")]
562-- Everything is escaped with @'escapeURIString' 'isUnreserved'@:
418-- Everything is escaped with @'escapeURIString' 'isUnreserved'@:
564−-- >>> urlEncodeFormStable [("fullname", "Andres Löh")]
420+-- >>> urlEncodeForm [("fullname", "Andres Löh")]
565-- "fullname=Andres%20L%C3%B6h"
421-- "fullname=Andres%20L%C3%B6h"
566−urlEncodeFormStable :: Form -> BSL.ByteString
422+urlEncodeForm :: Form -> BSL.ByteString
567−urlEncodeFormStable = urlEncodeParams . sortOn fst . toList
569−-- | Encode a list of key-value pairs to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
571−-- See also 'urlEncodeFormStable'.
572−urlEncodeParams :: [(Text, Text)] -> BSL.ByteString
573−urlEncodeParams = toLazyByteString . mconcat . intersperse (shortByteString "&") . map encodePair
423+urlEncodeForm = toLazyByteString . mconcat . intersperse (shortByteString "&") . map encodePair . toList
575− escape = urlEncodeBuilder True . Text.encodeUtf8
425+ escape = urlEncodeQuery . Text.encodeUtf8
577 encodePair (k, "") = escape k
427 encodePair (k, "") = escape k
578− encodePair (k, v) = escape k <> shortByteString "=" <> escape v
428+ encodePair (k, v) = escape k <> shortByteString "=" <> escape v
580-- | Decode an @application/x-www-form-urlencoded@ 'BSL.ByteString' to a 'Form'.
431-- | Decode an @application/x-www-form-urlencoded@ 'BSL.ByteString' to a 'Form'.
@@ -609,17 +460,11 @@ urlEncodeParams = toLazyByteString . mconcat . intersperse (shortByteString "&")
609-- >>> urlDecodeForm "this=has=too=many=equals"
460-- >>> urlDecodeForm "this=has=too=many=equals"
610-- Left "not a valid pair: this=has=too=many=equals"
461-- Left "not a valid pair: this=has=too=many=equals"
611urlDecodeForm :: BSL.ByteString -> Either Text Form
462urlDecodeForm :: BSL.ByteString -> Either Text Form
612−urlDecodeForm = fmap toForm . urlDecodeParams
614−-- | Decode an @application/x-www-form-urlencoded@ 'BSL.ByteString' to a list of key-value pairs.
616−-- See also 'urlDecodeForm'.
617−urlDecodeParams :: BSL.ByteString -> Either Text [(Text, Text)]
618−urlDecodeParams bs = traverse parsePair pairs
463+urlDecodeForm bs = toForm <$> traverse parsePair pairs
620 pairs = map (BSL8.split '=') (BSL8.split '&' bs)
465 pairs = map (BSL8.split '=') (BSL8.split '&' bs)
622− unescape = Text.decodeUtf8With lenientDecode . urlDecode True . BSL.toStrict
467+ unescape = Text.decodeUtf8With lenientDecode . urlDecodeQuery . BSL.toStrict
624 parsePair p =
469 parsePair p =
625 case map unescape p of
470 case map unescape p of
@@ -627,7 +472,6 @@ urlDecodeParams bs = traverse parsePair pairs
627 [k] -> return (k, "")
472 [k] -> return (k, "")
628 xs -> Left $ "not a valid pair: " <> Text.intercalate "=" xs
473 xs -> Left $ "not a valid pair: " <> Text.intercalate "=" xs
631-- | This is a convenience function for decoding a
475-- | This is a convenience function for decoding a
632-- @application/x-www-form-urlencoded@ 'BSL.ByteString' directly to a datatype
476-- @application/x-www-form-urlencoded@ 'BSL.ByteString' directly to a datatype
633-- that has an instance of 'FromForm'.
477-- that has an instance of 'FromForm'.
@@ -645,22 +489,11 @@ urlDecodeAsForm = fromForm <=< urlDecodeForm
646-- This is effectively @'urlEncodeForm' . 'toForm'@.
490-- This is effectively @'urlEncodeForm' . 'toForm'@.
648−-- _NOTE:_ this encoding is unstable and may result in different key order
492+-- >>> urlEncodeAsForm Person {name = "Dennis", age = 22}
649−-- (but not values). For a stable encoding see 'urlEncodeAsFormStable'.
493+-- "age=22&name=Dennis"
650urlEncodeAsForm :: ToForm a => a -> BSL.ByteString
494urlEncodeAsForm :: ToForm a => a -> BSL.ByteString
651urlEncodeAsForm = urlEncodeForm . toForm
495urlEncodeAsForm = urlEncodeForm . toForm
653−-- | This is a convenience function for encoding a datatype that has instance
654−-- of 'ToForm' directly to a @application/x-www-form-urlencoded@
657−-- This is effectively @'urlEncodeFormStable' . 'toForm'@.
659−-- >>> urlEncodeAsFormStable Person {name = "Dennis", age = 22}
660−-- "age=22&name=Dennis"
661−urlEncodeAsFormStable :: ToForm a => a -> BSL.ByteString
662−urlEncodeAsFormStable = urlEncodeFormStable . toForm
664-- | Find all values corresponding to a given key in a 'Form'.
497-- | Find all values corresponding to a given key in a 'Form'.
666-- >>> lookupAll "name" []
499-- >>> lookupAll "name" []
@@ -672,22 +505,6 @@ urlEncodeAsFormStable = urlEncodeFormStable . toForm
672lookupAll :: Text -> Form -> [Text]
505lookupAll :: Text -> Form -> [Text]
673lookupAll key = F.concat . HashMap.lookup key . unForm
506lookupAll key = F.concat . HashMap.lookup key . unForm
675−-- | Lookup an optional value for a key.
676−-- Fail if there is more than one value.
678−-- >>> lookupMaybe "name" []
680−-- >>> lookupMaybe "name" [("name", "Oleg")]
681−-- Right (Just "Oleg")
682−-- >>> lookupMaybe "name" [("name", "Oleg"), ("name", "David")]
683−-- Left "Duplicate key \"name\""
684−lookupMaybe :: Text -> Form -> Either Text (Maybe Text)
685−lookupMaybe key form =
686− case lookupAll key form of
688− [v] -> pure (Just v)
689− _ -> Left $ "Duplicate key " <> Text.pack (show key)
691-- | Lookup a unique value for a key.
508-- | Lookup a unique value for a key.
692-- Fail if there is zero or more than one value.
509-- Fail if there is zero or more than one value.
@@ -698,11 +515,11 @@ lookupMaybe key form =
698-- >>> lookupUnique "name" [("name", "Oleg"), ("name", "David")]
515-- >>> lookupUnique "name" [("name", "Oleg"), ("name", "David")]
699-- Left "Duplicate key \"name\""
516-- Left "Duplicate key \"name\""
700lookupUnique :: Text -> Form -> Either Text Text
517lookupUnique :: Text -> Form -> Either Text Text
701−lookupUnique key form = do
518+lookupUnique key form =
702− mv <- lookupMaybe key form
703− case mv of
519+ case lookupAll key form of
704− Just v -> pure v
520+ [v] -> pure v
705− Nothing -> Left $ "Could not find key " <> Text.pack (show key)
521+ [] -> Left $ "Could not find key " <> Text.pack (show key)
522+ _ -> Left $ "Duplicate key " <> Text.pack (show key)
707-- | Lookup all values for a given key in a 'Form' and parse them with 'parseQueryParams'.
524-- | Lookup all values for a given key in a 'Form' and parse them with 'parseQueryParams'.
@@ -717,22 +534,6 @@ lookupUnique key form = do
717parseAll :: FromHttpApiData v => Text -> Form -> Either Text [v]
534parseAll :: FromHttpApiData v => Text -> Form -> Either Text [v]
718parseAll key = parseQueryParams . lookupAll key
535parseAll key = parseQueryParams . lookupAll key
720−-- | Lookup an optional value for a given key and parse it with 'parseQueryParam'.
721−-- Fail if there is more than one value for the key.
723−-- >>> parseMaybe "age" [] :: Either Text (Maybe Word8)
725−-- >>> parseMaybe "age" [("age", "12"), ("age", "25")] :: Either Text (Maybe Word8)
726−-- Left "Duplicate key \"age\""
727−-- >>> parseMaybe "age" [("age", "seven")] :: Either Text (Maybe Word8)
728−-- Left "could not parse: `seven' (input does not start with a digit)"
729−-- >>> parseMaybe "age" [("age", "777")] :: Either Text (Maybe Word8)
730−-- Left "out of bounds: `777' (should be between 0 and 255)"
731−-- >>> parseMaybe "age" [("age", "7")] :: Either Text (Maybe Word8)
733−parseMaybe :: FromHttpApiData v => Text -> Form -> Either Text (Maybe v)
734−parseMaybe key = parseQueryParams <=< lookupMaybe key
736-- | Lookup a unique value for a given key and parse it with 'parseQueryParam'.
537-- | Lookup a unique value for a given key and parse it with 'parseQueryParam'.
737-- Fail if there is zero or more than one value for the key.
538-- Fail if there is zero or more than one value for the key.
@@ -750,31 +551,6 @@ parseUnique :: FromHttpApiData v => Text -> Form -> Either Text v
750parseUnique key form = lookupUnique key form >>= parseQueryParam
551parseUnique key form = lookupUnique key form >>= parseQueryParam
752-- | 'Generic'-based deriving options for 'ToForm' and 'FromForm'.
553-- | 'Generic'-based deriving options for 'ToForm' and 'FromForm'.
754−-- A common use case for non-default 'FormOptions'
755−-- is to strip a prefix off of field labels:
758−-- data Project = Project
759−-- { projectName :: String
760−-- , projectSize :: Int
761−-- } deriving ('Generic', 'Show')
763−-- myOptions :: 'FormOptions'
764−-- myOptions = 'FormOptions'
765−-- { 'fieldLabelModifier' = 'map' 'toLower' . 'drop' ('length' \"project\") }
767−-- instance 'ToForm' Project where
768−-- 'toForm' = 'genericToForm' myOptions
770−-- instance 'FromForm' Project where
771−-- 'fromForm' = 'genericFromForm' myOptions
774−-- >>> urlEncodeAsFormStable Project { projectName = "http-api-data", projectSize = 172 }
775−-- "name=http-api-data&size=172"
776−-- >>> urlDecodeAsForm "name=http-api-data&size=172" :: Either Text Project
777−-- Right (Project {projectName = "http-api-data", projectSize = 172})
778data FormOptions = FormOptions
554data FormOptions = FormOptions
779 { -- | Function applied to field labels. Handy for removing common record prefixes for example.
555 { -- | Function applied to field labels. Handy for removing common record prefixes for example.
780 fieldLabelModifier :: String -> String
556 fieldLabelModifier :: String -> String
@@ -791,6 +567,3 @@ defaultFormOptions :: FormOptions
791defaultFormOptions = FormOptions
567defaultFormOptions = FormOptions
792 { fieldLabelModifier = id
568 { fieldLabelModifier = id
795−sortOn :: Ord b => (a -> b) -> [a] -> [a]
796−sortOn f = sortBy (comparing f)