@@ -1,58 +1,67 @@
1+{-# LANGUAGE ConstraintKinds #-}
12{-# LANGUAGE CPP #-}
3+{-# LANGUAGE DataKinds #-}
24{-# LANGUAGE DefaultSignatures #-}
35{-# LANGUAGE DeriveGeneric #-}
46{-# LANGUAGE FlexibleContexts #-}
57{-# LANGUAGE FlexibleInstances #-}
68{-# LANGUAGE GeneralizedNewtypeDeriving #-}
79{-# LANGUAGE KindSignatures #-}
10+{-# LANGUAGE MultiParamTypeClasses #-}
811{-# LANGUAGE OverloadedStrings #-}
912{-# LANGUAGE PolyKinds #-}
1013{-# LANGUAGE ScopedTypeVariables #-}
1114{-# LANGUAGE TypeFamilies #-}
1215{-# LANGUAGE TypeOperators #-}
16+{-# LANGUAGE UndecidableInstances #-}
17+#include "overlapping-compat.h"
1318module Web.Internal.FormUrlEncoded where
1419
15−#if __GLASGOW_HASKELL__ < 710
16−import Control.Applicative
17−import Data.Traversable
18−#endif
20+import Prelude ()
21+import Prelude.Compat
1922
23+import Control.Applicative (Const(Const))
2024import Control.Arrow ((***))
2125import Control.Monad ((<=<))
22−import Data.ByteString.Builder (toLazyByteString, shortByteString)
26+import Data.ByteString.Builder (shortByteString, toLazyByteString)
2327import qualified Data.ByteString.Lazy as BSL
2428import qualified Data.ByteString.Lazy.Char8 as BSL8
29+import Data.Coerce (coerce)
2530import qualified Data.Foldable as F
31+import Data.Functor.Identity (Identity(Identity))
2632import Data.Hashable (Hashable)
2733import Data.HashMap.Strict (HashMap)
2834import qualified Data.HashMap.Strict as HashMap
29−import Data.Int
35+import Data.Int (Int16, Int32, Int64, Int8)
3036import Data.IntMap (IntMap)
3137import qualified Data.IntMap as IntMap
32−import Data.List (intersperse)
38+import Data.List (intersperse, sortBy)
3339import Data.Map (Map)
3440import qualified Data.Map as Map
35−import Data.Monoid
36−
41+import Data.Monoid (All (..), Any (..), Dual (..),
42+ Product (..), Sum (..))
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 (..))
3748import Data.Text (Text)
3849import qualified Data.Text as Text
39−import qualified Data.Text.Lazy as Lazy
40−import Data.Text.Encoding as Text
50+import qualified Data.Text.Encoding as Text
4151import Data.Text.Encoding.Error (lenientDecode)
42−
43−import Data.Time
44−import Data.Word
45−
46−#if MIN_VERSION_base(4,8,0)
47−import Data.Void
48−import Numeric.Natural
49−#endif
50−
51−import GHC.Exts (IsList (..))
52+import qualified Data.Text.Lazy as Lazy
53+import Data.Time.Compat (Day, LocalTime, NominalDiffTime,
54+ UTCTime, ZonedTime)
55+import Data.Time.Calendar.Month.Compat (Month)
56+import Data.Time.Calendar.Quarter.Compat (Quarter, QuarterOfYear (..))
57+import Data.Void (Void)
58+import Data.Word (Word16, Word32, Word64, Word8)
59+import GHC.Exts (Constraint, IsList (..))
5260import GHC.Generics
53−import URI.ByteString (urlEncodeQuery, urlDecodeQuery)
54−
55−import Web.Internal.HttpApiData
61+import GHC.TypeLits
62+import Network.HTTP.Types.URI (urlDecode, urlEncodeBuilder)
63+import Numeric.Natural (Natural)
64+import Web.Internal.HttpApiData
5665
5766-- $setup
5867-- >>> :set -XDeriveGeneric
@@ -61,11 +70,20 @@ import Web.Internal.HttpApiData
6170-- >>> :set -XFlexibleContexts
6271-- >>> :set -XScopedTypeVariables
6372-- >>> :set -XTypeFamilies
64−-- >>> import Data.Either (isLeft)
65−-- >>> import Data.List (sort)
73+-- >>> import Data.Char (toLower)
74+--
6675-- >>> data Person = Person { name :: String, age :: Int } deriving (Show, Generic)
6776-- >>> instance ToForm Person
6877-- >>> instance FromForm Person
78+--
79+-- >>> data Post = Post { title :: String, subtitle :: Maybe String, comments :: [String]} deriving (Generic, Show)
80+-- >>> instance ToForm Post
81+-- >>> instance FromForm Post
82+--
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
6987
7088-- | Typeclass for types that can be used as keys in a 'Form'-like container (like 'Map').
7189class ToFormKey k where
@@ -97,6 +115,9 @@ instance ToFormKey LocalTime where toFormKey = toQueryParam
97115instance ToFormKey ZonedTime where toFormKey = toQueryParam
98116instance ToFormKey UTCTime where toFormKey = toQueryParam
99117instance 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
100121
101122instance ToFormKey String where toFormKey = toQueryParam
102123instance ToFormKey Text where toFormKey = toQueryParam
@@ -105,14 +126,26 @@ instance ToFormKey Lazy.Text where toFormKey = toQueryParam
105126instance ToFormKey All where toFormKey = toQueryParam
106127instance ToFormKey Any where toFormKey = toQueryParam
107128
108−instance ToFormKey a => ToFormKey (Dual a) where toFormKey = toFormKey . getDual
109−instance ToFormKey a => ToFormKey (Sum a) where toFormKey = toFormKey . getSum
110−instance ToFormKey a => ToFormKey (Product a) where toFormKey = toFormKey . getProduct
129+instance ToFormKey a => ToFormKey (Dual a) where toFormKey = coerce (toFormKey :: a -> Text)
130+instance ToFormKey a => ToFormKey (Sum a) where toFormKey = coerce (toFormKey :: a -> Text)
131+instance ToFormKey a => ToFormKey (Product a) where toFormKey = coerce (toFormKey :: a -> Text)
132+
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)
137+
138+instance ToFormKey a => ToFormKey (Tagged b a) where toFormKey = coerce (toFormKey :: a -> Text)
139+
140+-- | @since 0.4.2
141+instance ToFormKey a => ToFormKey (Identity a) where toFormKey = coerce (toFormKey :: a -> Text)
142+
143+-- | @since 0.4.2
144+instance ToFormKey a => ToFormKey (Const a b) where
145+ toFormKey = coerce (toFormKey :: a -> Text)
111146
112−#if MIN_VERSION_base(4,8,0)
113147instance ToFormKey Void where toFormKey = toQueryParam
114148instance ToFormKey Natural where toFormKey = toQueryParam
115−#endif
116149
117150-- | Typeclass for types that can be parsed from keys of a 'Form'. This is the reverse of 'ToFormKey'.
118151class FromFormKey k where
@@ -144,6 +177,9 @@ instance FromFormKey LocalTime where parseFormKey = parseQueryParam
144177instance FromFormKey ZonedTime where parseFormKey = parseQueryParam
145178instance FromFormKey UTCTime where parseFormKey = parseQueryParam
146179instance 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
147183
148184instance FromFormKey String where parseFormKey = parseQueryParam
149185instance FromFormKey Text where parseFormKey = parseQueryParam
@@ -152,30 +188,48 @@ instance FromFormKey Lazy.Text where parseFormKey = parseQueryParam
152188instance FromFormKey All where parseFormKey = parseQueryParam
153189instance FromFormKey Any where parseFormKey = parseQueryParam
154190
155−instance FromFormKey a => FromFormKey (Dual a) where parseFormKey = fmap Dual . parseFormKey
156−instance FromFormKey a => FromFormKey (Sum a) where parseFormKey = fmap Sum . parseFormKey
157−instance FromFormKey a => FromFormKey (Product a) where parseFormKey = fmap Product . parseFormKey
191+instance FromFormKey a => FromFormKey (Dual a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
192+instance FromFormKey a => FromFormKey (Sum a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
193+instance FromFormKey a => FromFormKey (Product a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
194+
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)
199+
200+instance FromFormKey a => FromFormKey (Tagged b a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
201+
202+-- | @since 0.4.2
203+instance FromFormKey a => FromFormKey (Identity a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
204+
205+-- | @since 0.4.2
206+instance FromFormKey a => FromFormKey (Const a b) where
207+ parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
158208
159−#if MIN_VERSION_base(4,8,0)
160209instance FromFormKey Void where parseFormKey = parseQueryParam
161210instance FromFormKey Natural where parseFormKey = parseQueryParam
162−#endif
163211
164212-- | The contents of a form, not yet URL-encoded.
165213--
166214-- 'Form' can be URL-encoded with 'urlEncodeForm' and URL-decoded with 'urlDecodeForm'.
167215newtype Form = Form { unForm :: HashMap Text [Text] }
168− deriving (Eq, Read, Generic, Monoid)
216+ deriving (Eq, Read, Generic, Semigroup, Monoid)
169217
170218instance Show Form where
171219 showsPrec d form = showParen (d > 10) $
172− showString "fromList " . shows (toList form)
220+ showString "fromList " . shows (toListStable form)
173221
222+-- | _NOTE:_ 'toList' is unstable and may result in different key order (but not values).
223+-- For a stable conversion use 'toListStable'.
174224instance IsList Form where
175225 type Item Form = (Text, Text)
176226 fromList = Form . HashMap.fromListWith (flip (<>)) . fmap (\(k, v) -> (k, [v]))
177227 toList = concatMap (\(k, vs) -> map ((,) k) vs) . HashMap.toList . unForm
178228
229+-- | A stable version of 'toList'.
230+toListStable :: Form -> [(Text, Text)]
231+toListStable = sortOn fst . toList
232+
179233-- | Convert a value into 'Form'.
180234--
181235-- An example type and instance:
@@ -212,12 +266,11 @@ instance IsList Form where
212266-- @
213267--
214268-- The default implementation of 'toForm' is 'genericToForm'.
215−-- It only works for records and it will use 'toQueryParam' for each field's value.
216269class ToForm a where
217270 -- | Convert a value into 'Form'.
218271 toForm :: a -> Form
219− default toForm :: (Generic a, GToForm (Rep a)) => a -> Form
220− toForm = genericToForm
272+ default toForm :: (Generic a, GToForm a (Rep a)) => a -> Form
273+ toForm = genericToForm defaultFormOptions
221274
222275instance ToForm Form where toForm = id
223276
@@ -242,6 +295,18 @@ fromEntriesByKey = Form . HashMap.fromListWith (<>) . map (toFormKey *** map toQ
242295
243296data Proxy3 a b c = Proxy3
244297
298+type family NotSupported (cls :: k1) (a :: k2) (reason :: Symbol) :: Constraint where
299+#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" = ()
302+#else
303+ NotSupported cls a reason = TypeError
304+ ( 'Text "Cannot derive a Generic-based " ':<>: 'ShowType cls ':<>: 'Text " instance for " ':<>: 'ShowType a ':<>: 'Text "." ':$$:
305+ 'ShowType a ':<>: 'Text " " ':<>: 'Text reason ':<>: 'Text "," ':$$:
306+ 'Text "but Generic-based " ':<>: 'ShowType cls ':<>: 'Text " instances can be derived only for records" ':$$:
307+ 'Text "(i.e. product types with named fields)." )
308+#endif
309+
245310-- | A 'Generic'-based implementation of 'toForm'.
246311-- This is used as a default implementation in 'ToForm'.
247312--
@@ -253,25 +318,69 @@ data Proxy3 a b c = Proxy3
253318-- , age :: Int
254319-- } deriving ('Generic')
255320-- @
256−genericToForm :: (Generic a, GToForm (Rep a)) => a -> Form
257−genericToForm = gToForm . from
321+--
322+-- In this implementation each field's value gets encoded using `toQueryParam`.
323+-- Two field types are exceptions:
324+--
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';
327+--
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';
330+--
331+-- Here's an example:
332+--
333+-- @
334+-- data Post = Post
335+-- { title :: String
336+-- , subtitle :: Maybe String
337+-- , comments :: [String]
338+-- } deriving ('Generic', 'Show')
339+--
340+-- instance 'ToForm' Post
341+-- @
342+--
343+-- >>> urlEncodeAsFormStable Post { title = "Test", subtitle = Nothing, comments = ["Nice post!", "+1"] }
344+-- "comments=Nice%20post%21&comments=%2B1&title=Test"
345+genericToForm :: forall a. (Generic a, GToForm a (Rep a)) => FormOptions -> a -> Form
346+genericToForm opts = gToForm (Proxy :: Proxy a) opts . from
258347
259−class GToForm (f :: * -> *) where
260− gToForm :: f x -> Form
348+class GToForm t (f :: * -> *) where
349+ gToForm :: Proxy t -> FormOptions -> f x -> Form
261350
262−instance (GToForm f, GToForm g) => GToForm (f :*: g) where
263− gToForm (a :*: b) = gToForm a <> gToForm b
351+instance (GToForm t f, GToForm t g) => GToForm t (f :*: g) where
352+ gToForm p opts (a :*: b) = gToForm p opts a <> gToForm p opts b
264353
265−instance (GToForm f) => GToForm (M1 D x f) where
266− gToForm (M1 a) = gToForm a
354+instance (GToForm t f) => GToForm t (M1 D x f) where
355+ gToForm p opts (M1 a) = gToForm p opts a
267356
268−instance (GToForm f) => GToForm (M1 C x f) where
269− gToForm (M1 a) = gToForm a
357+instance (GToForm t f) => GToForm t (M1 C x f) where
358+ gToForm p opts (M1 a) = gToForm p opts a
270359
271−instance (Selector s, ToHttpApiData c) => GToForm (M1 S s (K1 i c)) where
272− gToForm (M1 (K1 c)) = fromList [(key, toQueryParam c)]
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)]
273362 where
274− key = Text.pack $ selName (Proxy3 :: Proxy3 s g p)
363+ key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
364+
365+instance (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i (Maybe c))) where
366+ gToForm _ opts (M1 (K1 c)) =
367+ case c of
368+ Nothing -> mempty
369+ Just x -> fromList [(key, toQueryParam x)]
370+ where
371+ key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
372+
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)
375+ where
376+ key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
377+
378+instance OVERLAPPING_ (Selector s) => GToForm t (M1 S s (K1 i String)) where
379+ gToForm _ opts (M1 (K1 c)) = fromList [(key, toQueryParam c)]
380+ where
381+ key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
382+
383+instance NotSupported ToForm t "is a sum type" => GToForm t (f :+: g) where gToForm = error "impossible"
275384
276385-- | Parse 'Form' into a value.
277386--
@@ -283,9 +392,9 @@ instance (Selector s, ToHttpApiData c) => GToForm (M1 S s (K1 i c)) where
283392-- , age :: Int }
284393--
285394-- instance 'FromForm' Person where
286−-- 'fromForm' (Form m) = Person
287−-- '<$>' 'parseUnique' "name" m
288−-- '<*>' 'parseUnique' "age" m
395+-- 'fromForm' f = Person
396+-- '<$>' 'parseUnique' "name" f
397+-- '<*>' 'parseUnique' "age" f
289398-- @
290399--
291400-- Instead of manually writing @'FromForm'@ instances you can
@@ -311,12 +420,12 @@ instance (Selector s, ToHttpApiData c) => GToForm (M1 S s (K1 i c)) where
311420class FromForm a where
312421 -- | Parse 'Form' into a value.
313422 fromForm :: Form -> Either Text a
314− default fromForm :: (Generic a, GFromForm (Rep a))
315− => Form -> Either Text a
316− fromForm = genericFromForm
423+ default fromForm :: (Generic a, GFromForm a (Rep a)) => Form -> Either Text a
424+ fromForm = genericFromForm defaultFormOptions
317425
318426instance FromForm Form where fromForm = pure
319427
428+-- | _NOTE:_ this conversion is unstable and may result in different key order (but not values).
320429instance (FromFormKey k, FromHttpApiData v) => FromForm [(k, v)] where
321430 fromForm = fmap (concatMap (\(k, vs) -> map ((,) k) vs)) . toEntriesByKey
322431
@@ -331,13 +440,22 @@ instance FromHttpApiData v => FromForm (IntMap [v]) where
331440
332441-- | Parse a 'Form' into a list of entries groupped by key.
333442--
334−-- >>> toEntriesByKey [("name", "Nick"), ("color", "red"), ("color", "white")] :: Either Text [(Text, [Text])]
335−-- Right [("color",["red","white"]),("name",["Nick"])]
443+-- _NOTE:_ this conversion is unstable and may result in different key order
444+-- (but not values). For a stable encoding see 'toEntriesByKeyStable'.
336445toEntriesByKey :: (FromFormKey k, FromHttpApiData v) => Form -> Either Text [(k, [v])]
337446toEntriesByKey = traverse parseGroup . HashMap.toList . unForm
338447 where
339448 parseGroup (k, vs) = (,) <$> parseFormKey k <*> traverse parseQueryParam vs
340449
450+-- | Parse a 'Form' into a list of entries groupped by key.
451+--
452+-- >>> toEntriesByKeyStable [("name", "Nick"), ("color", "red"), ("color", "white")] :: Either Text [(Text, [Text])]
453+-- Right [("color",["red","white"]),("name",["Nick"])]
454+--
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
458+
341459-- | A 'Generic'-based implementation of 'fromForm'.
342460-- This is used as a default implementation in 'FromForm'.
343461--
@@ -349,62 +467,115 @@ toEntriesByKey = traverse parseGroup . HashMap.toList . unForm
349467-- , age :: Int
350468-- } deriving ('Generic')
351469-- @
352−genericFromForm :: (Generic a, GFromForm (Rep a))
353− => Form -> Either Text a
354−genericFromForm f = to <$> gFromForm f
470+--
471+-- In this implementation each field's value gets decoded using `parseQueryParam`.
472+-- Two field types are exceptions:
473+--
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';
476+--
477+-- - for values of type @[a]@ (except @['Char']@) all entries are parsed to produce a list of parsed values;
478+--
479+-- Here's an example:
480+--
481+-- @
482+-- data Post = Post
483+-- { title :: String
484+-- , subtitle :: Maybe String
485+-- , comments :: [String]
486+-- } deriving ('Generic', 'Show')
487+--
488+-- instance 'FromForm' Post
489+-- @
490+--
491+-- >>> urlDecodeAsForm "comments=Nice%20post%21&comments=%2B1&title=Test" :: Either Text Post
492+-- Right (Post {title = "Test", subtitle = Nothing, comments = ["Nice post!","+1"]})
493+genericFromForm :: forall a. (Generic a, GFromForm a (Rep a)) => FormOptions -> Form -> Either Text a
494+genericFromForm opts f = to <$> gFromForm (Proxy :: Proxy a) opts f
495+
496+class GFromForm t (f :: * -> *) where
497+ gFromForm :: Proxy t -> FormOptions -> Form -> Either Text (f x)
498+
499+instance (GFromForm t f, GFromForm t g) => GFromForm t (f :*: g) where
500+ gFromForm p opts f = (:*:) <$> gFromForm p opts f <*> gFromForm p opts f
501+
502+instance GFromForm t f => GFromForm t (M1 D x f) where
503+ gFromForm p opts f = M1 <$> gFromForm p opts f
504+
505+instance GFromForm t f => GFromForm t (M1 C x f) where
506+ gFromForm p opts f = M1 <$> gFromForm p opts f
507+
508+instance OVERLAPPABLE_ (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i c)) where
509+ gFromForm _ opts form = M1 . K1 <$> parseUnique key form
510+ where
511+ key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
355512
356−class GFromForm (f :: * -> *) where
357− gFromForm :: Form -> Either Text (f x)
513+instance (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i (Maybe c))) where
514+ gFromForm _ opts form = M1 . K1 <$> parseMaybe key form
515+ where
516+ key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
358517
359−instance (GFromForm f, GFromForm g) => GFromForm (f :*: g) where
360− gFromForm f = (:*:) <$> gFromForm f <*> gFromForm f
518+instance (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i [c])) where
519+ gFromForm _ opts form = M1 . K1 <$> parseAll key form
520+ where
521+ key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
361522
362−instance (Selector s, FromHttpApiData f) => GFromForm (M1 S s (K1 i f)) where
363− gFromForm form = M1 . K1 <$> parseUnique key form
523+instance OVERLAPPING_ (Selector s) => GFromForm t (M1 S s (K1 i String)) where
524+ gFromForm _ opts form = M1 . K1 <$> parseUnique key form
364525 where
365− key = Text.pack $ selName (Proxy3 :: Proxy3 s g p)
526+ key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
366527
367−instance (GFromForm f) => GFromForm (M1 D x f) where
368− gFromForm f = M1 <$> gFromForm f
528+instance NotSupported FromForm t "is a sum type" => GFromForm t (f :+: g) where gFromForm = error "impossible"
369529
370−instance (GFromForm f) => GFromForm (M1 C x f) where
371− gFromForm f = M1 <$> gFromForm f
530+-- | Encode a 'Form' to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
531+--
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
372536
373537-- | Encode a 'Form' to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
374538--
539+-- For an unstable (but faster) encoding see 'urlEncodeForm'.
540+--
375541-- Key-value pairs get encoded to @key=value@ and separated by @&@:
376542--
377−-- >>> urlEncodeForm [("name", "Julian"), ("lastname", "Arni")]
543+-- >>> urlEncodeFormStable [("name", "Julian"), ("lastname", "Arni")]
378544-- "lastname=Arni&name=Julian"
379545--
380546-- Keys with empty values get encoded to just @key@ (without the @=@ sign):
381547--
382−-- >>> urlEncodeForm [("is_test", "")]
548+-- >>> urlEncodeFormStable [("is_test", "")]
383549-- "is_test"
384550--
385551-- Empty keys are allowed too:
386552--
387−-- >>> urlEncodeForm [("", "foobar")]
553+-- >>> urlEncodeFormStable [("", "foobar")]
388554-- "=foobar"
389555--
390−-- However, if not key and value are empty, the key-value pair is ignored.
391−-- (This prevents @'urlDecodeForm' . 'urlEncodeForm'@ from being a true isomorphism).
556+-- However, if both key and value are empty, the key-value pair is ignored.
557+-- (This prevents @'urlDecodeForm' . 'urlEncodeFormStable'@ from being a true isomorphism).
392558--
393−-- >>> urlEncodeForm [("", "")]
559+-- >>> urlEncodeFormStable [("", "")]
394560-- ""
395561--
396562-- Everything is escaped with @'escapeURIString' 'isUnreserved'@:
397563--
398−-- >>> urlEncodeForm [("fullname", "Andres Löh")]
564+-- >>> urlEncodeFormStable [("fullname", "Andres Löh")]
399565-- "fullname=Andres%20L%C3%B6h"
400−urlEncodeForm :: Form -> BSL.ByteString
401−urlEncodeForm = toLazyByteString . mconcat . intersperse (shortByteString "&") . map encodePair . toList
566+urlEncodeFormStable :: Form -> BSL.ByteString
567+urlEncodeFormStable = urlEncodeParams . sortOn fst . toList
568+
569+-- | Encode a list of key-value pairs to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
570+--
571+-- See also 'urlEncodeFormStable'.
572+urlEncodeParams :: [(Text, Text)] -> BSL.ByteString
573+urlEncodeParams = toLazyByteString . mconcat . intersperse (shortByteString "&") . map encodePair
402574 where
403− escape = urlEncodeQuery . Text.encodeUtf8
575+ escape = urlEncodeBuilder True . Text.encodeUtf8
404576
405577 encodePair (k, "") = escape k
406− encodePair (k, v) = escape k <> shortByteString "=" <> escape v
407−
578+ encodePair (k, v) = escape k <> shortByteString "=" <> escape v
408579
409580-- | Decode an @application/x-www-form-urlencoded@ 'BSL.ByteString' to a 'Form'.
410581--
@@ -438,11 +609,17 @@ urlEncodeForm = toLazyByteString . mconcat . intersperse (shortByteString "&") .
438609-- >>> urlDecodeForm "this=has=too=many=equals"
439610-- Left "not a valid pair: this=has=too=many=equals"
440611urlDecodeForm :: BSL.ByteString -> Either Text Form
441−urlDecodeForm bs = toForm <$> traverse parsePair pairs
612+urlDecodeForm = fmap toForm . urlDecodeParams
613+
614+-- | Decode an @application/x-www-form-urlencoded@ 'BSL.ByteString' to a list of key-value pairs.
615+--
616+-- See also 'urlDecodeForm'.
617+urlDecodeParams :: BSL.ByteString -> Either Text [(Text, Text)]
618+urlDecodeParams bs = traverse parsePair pairs
442619 where
443620 pairs = map (BSL8.split '=') (BSL8.split '&' bs)
444621
445− unescape = Text.decodeUtf8With lenientDecode . urlDecodeQuery . BSL.toStrict
622+ unescape = Text.decodeUtf8With lenientDecode . urlDecode True . BSL.toStrict
446623
447624 parsePair p =
448625 case map unescape p of
@@ -450,6 +627,7 @@ urlDecodeForm bs = toForm <$> traverse parsePair pairs
450627 [k] -> return (k, "")
451628 xs -> Left $ "not a valid pair: " <> Text.intercalate "=" xs
452629
630+
453631-- | This is a convenience function for decoding a
454632-- @application/x-www-form-urlencoded@ 'BSL.ByteString' directly to a datatype
455633-- that has an instance of 'FromForm'.
@@ -467,11 +645,22 @@ urlDecodeAsForm = fromForm <=< urlDecodeForm
467645--
468646-- This is effectively @'urlEncodeForm' . 'toForm'@.
469647--
470−-- >>> urlEncodeAsForm Person {name = "Dennis", age = 22}
471−-- "age=22&name=Dennis"
648+-- _NOTE:_ this encoding is unstable and may result in different key order
649+-- (but not values). For a stable encoding see 'urlEncodeAsFormStable'.
472650urlEncodeAsForm :: ToForm a => a -> BSL.ByteString
473651urlEncodeAsForm = urlEncodeForm . toForm
474652
653+-- | This is a convenience function for encoding a datatype that has instance
654+-- of 'ToForm' directly to a @application/x-www-form-urlencoded@
655+-- 'BSL.ByteString'.
656+--
657+-- This is effectively @'urlEncodeFormStable' . 'toForm'@.
658+--
659+-- >>> urlEncodeAsFormStable Person {name = "Dennis", age = 22}
660+-- "age=22&name=Dennis"
661+urlEncodeAsFormStable :: ToForm a => a -> BSL.ByteString
662+urlEncodeAsFormStable = urlEncodeFormStable . toForm
663+
475664-- | Find all values corresponding to a given key in a 'Form'.
476665--
477666-- >>> lookupAll "name" []
@@ -483,6 +672,22 @@ urlEncodeAsForm = urlEncodeForm . toForm
483672lookupAll :: Text -> Form -> [Text]
484673lookupAll key = F.concat . HashMap.lookup key . unForm
485674
675+-- | Lookup an optional value for a key.
676+-- Fail if there is more than one value.
677+--
678+-- >>> lookupMaybe "name" []
679+-- Right Nothing
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
687+ [] -> pure Nothing
688+ [v] -> pure (Just v)
689+ _ -> Left $ "Duplicate key " <> Text.pack (show key)
690+
486691-- | Lookup a unique value for a key.
487692-- Fail if there is zero or more than one value.
488693--
@@ -493,11 +698,11 @@ lookupAll key = F.concat . HashMap.lookup key . unForm
493698-- >>> lookupUnique "name" [("name", "Oleg"), ("name", "David")]
494699-- Left "Duplicate key \"name\""
495700lookupUnique :: Text -> Form -> Either Text Text
496−lookupUnique key form =
497− case lookupAll key form of
498− [v] -> pure v
499− [] -> Left $ "Could not find key " <> Text.pack (show key)
500− _ -> Left $ "Duplicate key " <> Text.pack (show key)
701+lookupUnique key form = do
702+ mv <- lookupMaybe key form
703+ case mv of
704+ Just v -> pure v
705+ Nothing -> Left $ "Could not find key " <> Text.pack (show key)
501706
502707-- | Lookup all values for a given key in a 'Form' and parse them with 'parseQueryParams'.
503708--
@@ -512,6 +717,22 @@ lookupUnique key form =
512717parseAll :: FromHttpApiData v => Text -> Form -> Either Text [v]
513718parseAll key = parseQueryParams . lookupAll key
514719
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.
722+--
723+-- >>> parseMaybe "age" [] :: Either Text (Maybe Word8)
724+-- Right Nothing
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)
732+-- Right (Just 7)
733+parseMaybe :: FromHttpApiData v => Text -> Form -> Either Text (Maybe v)
734+parseMaybe key = parseQueryParams <=< lookupMaybe key
735+
515736-- | Lookup a unique value for a given key and parse it with 'parseQueryParam'.
516737-- Fail if there is zero or more than one value for the key.
517738--
@@ -528,3 +749,48 @@ parseAll key = parseQueryParams . lookupAll key
528749parseUnique :: FromHttpApiData v => Text -> Form -> Either Text v
529750parseUnique key form = lookupUnique key form >>= parseQueryParam
530751
752+-- | 'Generic'-based deriving options for 'ToForm' and 'FromForm'.
753+--
754+-- A common use case for non-default 'FormOptions'
755+-- is to strip a prefix off of field labels:
756+--
757+-- @
758+-- data Project = Project
759+-- { projectName :: String
760+-- , projectSize :: Int
761+-- } deriving ('Generic', 'Show')
762+--
763+-- myOptions :: 'FormOptions'
764+-- myOptions = 'FormOptions'
765+-- { 'fieldLabelModifier' = 'map' 'toLower' . 'drop' ('length' \"project\") }
766+--
767+-- instance 'ToForm' Project where
768+-- 'toForm' = 'genericToForm' myOptions
769+--
770+-- instance 'FromForm' Project where
771+-- 'fromForm' = 'genericFromForm' myOptions
772+-- @
773+--
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})
778+data FormOptions = FormOptions
779+ { -- | Function applied to field labels. Handy for removing common record prefixes for example.
780+ fieldLabelModifier :: String -> String
781+ }
782+
783+-- | Default encoding 'FormOptions'.
784+--
785+-- @
786+-- 'FormOptions'
787+-- { 'fieldLabelModifier' = id
788+-- }
789+-- @
790+defaultFormOptions :: FormOptions
791+defaultFormOptions = FormOptions
792+ { fieldLabelModifier = id
793+ }
794+
795+sortOn :: Ord b => (a -> b) -> [a] -> [a]
796+sortOn f = sortBy (comparing f)