|
| 1 | +{-# LANGUAGE CPP #-} |
| 2 | +{-# LANGUAGE UndecidableInstances #-} |
| 3 | + |
| 4 | +module Functora.Uri.ToQuery (ToQuery (..)) where |
| 5 | + |
| 6 | +import Functora.Prelude |
| 7 | +import GHC.Generics hiding (from) |
| 8 | +import qualified GHC.Generics as G |
| 9 | +import Text.URI |
| 10 | +import qualified Toml |
| 11 | +#if defined(__GHCJS__) && defined(ghcjs_HOST_OS) && defined(wasi_HOST_OS) |
| 12 | +import Data.JSString (JSString) |
| 13 | +#endif |
| 14 | + |
| 15 | +class (Typeable a) => ToQuery a where |
| 16 | + toQuery :: a -> [QueryParam] |
| 17 | + default toQuery :: (Generic a, GToQuery (Rep a)) => a -> [QueryParam] |
| 18 | + toQuery = gToQuery (Toml.stripTypeNamePrefix $ Proxy @a) . G.from |
| 19 | + |
| 20 | +class GToQuery f where |
| 21 | + gToQuery :: (String -> String) -> f p -> [QueryParam] |
| 22 | + |
| 23 | +-- Handle datatype metadata |
| 24 | +instance (GToQuery a) => GToQuery (M1 D c a) where |
| 25 | + gToQuery fmt (M1 x) = gToQuery fmt x |
| 26 | + |
| 27 | +-- Handle constructor metadata |
| 28 | +instance (GToQuery a) => GToQuery (M1 C c a) where |
| 29 | + gToQuery fmt (M1 x) = gToQuery fmt x |
| 30 | + |
| 31 | +instance (Selector s, ToQueryField a) => GToQuery (M1 S s (K1 i a)) where |
| 32 | + gToQuery fmt m1@(M1 (K1 a)) = do |
| 33 | + let name = selName m1 |
| 34 | + if null name |
| 35 | + then mempty -- Skip if there is no field name (like unnamed tuples) |
| 36 | + else do |
| 37 | + k <- mkQueryKey . pack $ fmt name |
| 38 | + v <- mkQueryValue $ toQueryField a |
| 39 | + pure $ QueryParam k v |
| 40 | + |
| 41 | +-- Handle product type |
| 42 | +instance (GToQuery a, GToQuery b) => GToQuery (a :*: b) where |
| 43 | + gToQuery fmt (a :*: b) = gToQuery fmt a ++ gToQuery fmt b |
| 44 | + |
| 45 | +class ToQueryField a where |
| 46 | + toQueryField :: a -> Text |
| 47 | + |
| 48 | +instance ToQueryField Text where |
| 49 | + toQueryField = id |
| 50 | + |
| 51 | +instance ToQueryField String where |
| 52 | + toQueryField = from @String @Text |
| 53 | + |
| 54 | +instance ToQueryField Int where |
| 55 | + toQueryField = inspect |
| 56 | + |
| 57 | +instance ToQueryField Integer where |
| 58 | + toQueryField = inspect |
| 59 | + |
| 60 | +#if defined(__GHCJS__) && defined(ghcjs_HOST_OS) && defined(wasi_HOST_OS) |
| 61 | +instance ToQueryField JSString where |
| 62 | + toQueryField = from @JSString @Text |
| 63 | +#endif |
0 commit comments