@@ -1,4 +1,5 @@
1{-# LANGUAGE ConstraintKinds #-}
1{-# LANGUAGE ConstraintKinds #-}
2{-# LANGUAGE DataKinds #-}
3{-# LANGUAGE DataKinds #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE FlexibleInstances #-}
@@ -6,7 +7,6 @@
6{-# LANGUAGE MultiParamTypeClasses #-}
7{-# LANGUAGE MultiParamTypeClasses #-}
7{-# LANGUAGE OverloadedStrings #-}
8{-# LANGUAGE OverloadedStrings #-}
8{-# LANGUAGE PolyKinds #-}
9{-# LANGUAGE PolyKinds #-}
9−{-# LANGUAGE QuantifiedConstraints #-}
10{-# LANGUAGE RankNTypes #-}
10{-# LANGUAGE RankNTypes #-}
11{-# LANGUAGE ScopedTypeVariables #-}
11{-# LANGUAGE ScopedTypeVariables #-}
12{-# LANGUAGE TypeApplications #-}
12{-# LANGUAGE TypeApplications #-}
@@ -14,13 +14,19 @@
14{-# LANGUAGE TypeOperators #-}
14{-# LANGUAGE TypeOperators #-}
15{-# LANGUAGE UndecidableInstances #-}
15{-# LANGUAGE UndecidableInstances #-}
17+#if MIN_VERSION_base(4,9,0) && __GLASGOW_HASKELL__ >= 802
18+#define HAS_TYPE_ERROR
21+#if __GLASGOW_HASKELL__ >= 806
22+{-# LANGUAGE QuantifiedConstraints #-}
17module Servant.Client.Core.HasClient (
25module Servant.Client.Core.HasClient (
19 HasClient (..),
27 HasClient (..),
20 EmptyClient (..),
28 EmptyClient (..),
21 AsClientT,
29 AsClientT,
24 foldMapUnion,
30 foldMapUnion,
25 matchUnion,
31 matchUnion,
@@ -33,7 +39,9 @@ import Control.Arrow
33import Control.Monad
39import Control.Monad
35import qualified Data.ByteString as BS
41import qualified Data.ByteString as BS
42+import Data.ByteString.Builder
36−import qualified Data.ByteString.Lazy as BL
44+import qualified Data.ByteString.Lazy as BL
37import Data.Either
45import Data.Either
38 (partitionEithers)
46 (partitionEithers)
39import Data.Constraint (Dict(..))
47import Data.Constraint (Dict(..))
@@ -45,8 +53,7 @@ import Data.Sequence
45 (fromList)
53 (fromList)
46import qualified Data.Text as T
54import qualified Data.Text as T
47import Network.HTTP.Media
55import Network.HTTP.Media
48− (MediaType, matches, parseAccept)
56+ (MediaType, matches, parseAccept, (//))
49−import qualified Network.HTTP.Media as Media
50import qualified Data.Sequence as Seq
57import qualified Data.Sequence as Seq
51import Data.SOP.BasicFunctors
58import Data.SOP.BasicFunctors
52 (I (I), (:.:) (Comp))
59 (I (I), (:.:) (Comp))
@@ -63,7 +70,7 @@ import Data.Text
63import Data.Proxy
70import Data.Proxy
64 (Proxy (Proxy))
71 (Proxy (Proxy))
65import GHC.TypeLits
72import GHC.TypeLits
66− (KnownNat, KnownSymbol, TypeError, symbolVal)
73+ (KnownSymbol, symbolVal)
67import Network.HTTP.Types
74import Network.HTTP.Types
69import qualified Network.HTTP.Types as H
76import qualified Network.HTTP.Types as H
@@ -84,12 +91,9 @@ import Servant.API.Generic
84 , GenericServant, toServant, fromServant)
91 , GenericServant, toServant, fromServant)
85import Servant.API.ContentTypes
92import Servant.API.ContentTypes
86 (contentTypes, AllMime (allMime), AllMimeUnrender (allMimeUnrender))
93 (contentTypes, AllMime (allMime), AllMimeUnrender (allMimeUnrender))
87−import Servant.API.Status
89import Servant.API.TypeLevel (FragmentUnique, AtLeastOneFragment)
94import Servant.API.TypeLevel (FragmentUnique, AtLeastOneFragment)
90import Servant.API.Modifiers
95import Servant.API.Modifiers
91 (FoldRequired, RequiredArgument, foldRequiredArgument)
96 (FoldRequired, RequiredArgument, foldRequiredArgument)
92−import Servant.API.TypeErrors
93import Servant.API.UVerb
97import Servant.API.UVerb
94 (HasStatus, HasStatuses (Statuses, statuses), UVerb, Union, Unique, inject, statusOf, foldMapUnion, matchUnion)
98 (HasStatus, HasStatuses (Statuses, statuses), UVerb, Union, Unique, inject, statusOf, foldMapUnion, matchUnion)
@@ -208,7 +212,7 @@ instance (KnownSymbol capture, ToHttpApiData a, HasClient m api)
208 clientWithRoute pm (Proxy :: Proxy api)
212 clientWithRoute pm (Proxy :: Proxy api)
209 (appendToPath p req)
213 (appendToPath p req)
211− where p = toEncodedUrlPiece val
215+ where p = (toUrlPiece val)
213 hoistClientMonad pm _ f cl = \a ->
217 hoistClientMonad pm _ f cl = \a ->
214 hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
218 hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
@@ -243,7 +247,7 @@ instance (KnownSymbol capture, ToHttpApiData a, HasClient m sublayout)
243 clientWithRoute pm (Proxy :: Proxy sublayout)
247 clientWithRoute pm (Proxy :: Proxy sublayout)
244 (foldl' (flip appendToPath) req ps)
248 (foldl' (flip appendToPath) req ps)
246− where ps = map toEncodedUrlPiece vals
250+ where ps = map (toUrlPiece) vals
248 hoistClientMonad pm _ f cl = \as ->
252 hoistClientMonad pm _ f cl = \as ->
249 hoistClientMonad pm (Proxy :: Proxy sublayout) f (cl as)
253 hoistClientMonad pm (Proxy :: Proxy sublayout) f (cl as)
@@ -251,11 +255,10 @@ instance (KnownSymbol capture, ToHttpApiData a, HasClient m sublayout)
251instance {-# OVERLAPPABLE #-}
255instance {-# OVERLAPPABLE #-}
252 -- Note [Non-Empty Content Types]
256 -- Note [Non-Empty Content Types]
253 ( RunClient m, MimeUnrender ct a, ReflectMethod method, cts' ~ (ct ': cts)
257 ( RunClient m, MimeUnrender ct a, ReflectMethod method, cts' ~ (ct ': cts)
255 ) => HasClient m (Verb method status cts' a) where
258 ) => HasClient m (Verb method status cts' a) where
256 type Client m (Verb method status cts' a) = m a
259 type Client m (Verb method status cts' a) = m a
257 clientWithRoute _pm Proxy req = do
260 clientWithRoute _pm Proxy req = do
258− response <- runRequestAcceptStatus (Just [status]) req
261+ response <- runRequest req
259 { requestAccept = fromList $ toList accept
262 { requestAccept = fromList $ toList accept
260 , requestMethod = method
263 , requestMethod = method
@@ -263,20 +266,18 @@ instance {-# OVERLAPPABLE #-}
264 accept = contentTypes (Proxy :: Proxy ct)
267 accept = contentTypes (Proxy :: Proxy ct)
265 method = reflectMethod (Proxy :: Proxy method)
268 method = reflectMethod (Proxy :: Proxy method)
266− status = statusFromNat (Proxy :: Proxy status)
268 hoistClientMonad _ _ f ma = f ma
270 hoistClientMonad _ _ f ma = f ma
270instance {-# OVERLAPPING #-}
272instance {-# OVERLAPPING #-}
271− ( RunClient m, ReflectMethod method, KnownNat status
273+ ( RunClient m, ReflectMethod method
272 ) => HasClient m (Verb method status cts NoContent) where
274 ) => HasClient m (Verb method status cts NoContent) where
273 type Client m (Verb method status cts NoContent)
275 type Client m (Verb method status cts NoContent)
274 = m NoContent
276 = m NoContent
275 clientWithRoute _pm Proxy req = do
277 clientWithRoute _pm Proxy req = do
276− _response <- runRequestAcceptStatus (Just [status]) req { requestMethod = method }
278+ _response <- runRequest req { requestMethod = method }
277 return NoContent
279 return NoContent
278 where method = reflectMethod (Proxy :: Proxy method)
280 where method = reflectMethod (Proxy :: Proxy method)
279− status = statusFromNat (Proxy :: Proxy status)
281 hoistClientMonad _ _ f ma = f ma
282 hoistClientMonad _ _ f ma = f ma
@@ -293,13 +294,13 @@ instance (RunClient m, ReflectMethod method) =>
294instance {-# OVERLAPPING #-}
295instance {-# OVERLAPPING #-}
295 -- Note [Non-Empty Content Types]
296 -- Note [Non-Empty Content Types]
296− ( RunClient m, MimeUnrender ct a, BuildHeadersTo ls, KnownNat status
297+ ( RunClient m, MimeUnrender ct a, BuildHeadersTo ls
297 , ReflectMethod method, cts' ~ (ct ': cts)
298 , ReflectMethod method, cts' ~ (ct ': cts)
298 ) => HasClient m (Verb method status cts' (Headers ls a)) where
299 ) => HasClient m (Verb method status cts' (Headers ls a)) where
299 type Client m (Verb method status cts' (Headers ls a))
300 type Client m (Verb method status cts' (Headers ls a))
300 = m (Headers ls a)
301 = m (Headers ls a)
301 clientWithRoute _pm Proxy req = do
302 clientWithRoute _pm Proxy req = do
302− response <- runRequestAcceptStatus (Just [status]) req
303+ response <- runRequest req
303 { requestMethod = method
304 { requestMethod = method
304 , requestAccept = fromList $ toList accept
305 , requestAccept = fromList $ toList accept
@@ -307,26 +308,22 @@ instance {-# OVERLAPPING #-}
307 return $ Headers { getResponse = val
308 return $ Headers { getResponse = val
308 , getHeadersHList = buildHeadersTo . toList $ responseHeaders response
309 , getHeadersHList = buildHeadersTo . toList $ responseHeaders response
311− method = reflectMethod (Proxy :: Proxy method)
311+ where method = reflectMethod (Proxy :: Proxy method)
312− accept = contentTypes (Proxy :: Proxy ct)
312+ accept = contentTypes (Proxy :: Proxy ct)
313− status = statusFromNat (Proxy :: Proxy status)
315 hoistClientMonad _ _ f ma = f ma
314 hoistClientMonad _ _ f ma = f ma
317instance {-# OVERLAPPING #-}
316instance {-# OVERLAPPING #-}
318− ( RunClient m, BuildHeadersTo ls, ReflectMethod method, KnownNat status
317+ ( RunClient m, BuildHeadersTo ls, ReflectMethod method
319 ) => HasClient m (Verb method status cts (Headers ls NoContent)) where
318 ) => HasClient m (Verb method status cts (Headers ls NoContent)) where
320 type Client m (Verb method status cts (Headers ls NoContent))
319 type Client m (Verb method status cts (Headers ls NoContent))
321 = m (Headers ls NoContent)
320 = m (Headers ls NoContent)
322 clientWithRoute _pm Proxy req = do
321 clientWithRoute _pm Proxy req = do
322+ let method = reflectMethod (Proxy :: Proxy method)
323− response <- runRequestAcceptStatus (Just [status]) req { requestMethod = method }
323+ response <- runRequest req { requestMethod = method }
324 return $ Headers { getResponse = NoContent
324 return $ Headers { getResponse = NoContent
325 , getHeadersHList = buildHeadersTo . toList $ responseHeaders response
325 , getHeadersHList = buildHeadersTo . toList $ responseHeaders response
328− method = reflectMethod (Proxy :: Proxy method)
329− status = statusFromNat (Proxy :: Proxy status)
331 hoistClientMonad _ _ f ma = f ma
328 hoistClientMonad _ _ f ma = f ma
@@ -569,7 +566,7 @@ instance (KnownSymbol sym, ToHttpApiData a, HasClient m api, SBoolI (FoldRequire
569 (Proxy :: Proxy mods) add (maybe req add) mparam
566 (Proxy :: Proxy mods) add (maybe req add) mparam
571 add :: a -> Request
568 add :: a -> Request
572− add param = appendToQueryString pname (Just $ encodeQueryParamValue param) req
569+ add param = appendToQueryString pname (Just $ encodeQueryParam param) req
574 pname :: Text
571 pname :: Text
575 pname = pack $ symbolVal (Proxy :: Proxy sym)
572 pname = pack $ symbolVal (Proxy :: Proxy sym)
@@ -577,6 +574,9 @@ instance (KnownSymbol sym, ToHttpApiData a, HasClient m api, SBoolI (FoldRequire
577 hoistClientMonad pm _ f cl = \arg ->
574 hoistClientMonad pm _ f cl = \arg ->
578 hoistClientMonad pm (Proxy :: Proxy api) f (cl arg)
575 hoistClientMonad pm (Proxy :: Proxy api) f (cl arg)
577+encodeQueryParam :: ToHttpApiData a => a -> BS.ByteString
578+encodeQueryParam = BL.toStrict . toLazyByteString . toEncodedUrlPiece
580-- | If you use a 'QueryParams' in one of your endpoints in your API,
580-- | If you use a 'QueryParams' in one of your endpoints in your API,
581-- the corresponding querying function will automatically take
581-- the corresponding querying function will automatically take
582-- an additional argument, a list of values of the type specified
582-- an additional argument, a list of values of the type specified
@@ -618,7 +618,7 @@ instance (KnownSymbol sym, ToHttpApiData a, HasClient m api)
620 where pname = pack $ symbolVal (Proxy :: Proxy sym)
620 where pname = pack $ symbolVal (Proxy :: Proxy sym)
621− paramlist' = map (Just . encodeQueryParamValue) paramlist
621+ paramlist' = map (Just . encodeQueryParam) paramlist
623 hoistClientMonad pm _ f cl = \as ->
623 hoistClientMonad pm _ f cl = \as ->
624 hoistClientMonad pm (Proxy :: Proxy api) f (cl as)
624 hoistClientMonad pm (Proxy :: Proxy api) f (cl as)
@@ -740,7 +740,7 @@ instance (KnownSymbol path, HasClient m api) => HasClient m (path :> api) where
740 clientWithRoute pm (Proxy :: Proxy api)
740 clientWithRoute pm (Proxy :: Proxy api)
741 (appendToPath p req)
741 (appendToPath p req)
743− where p = toEncodedUrlPiece $ pack $ symbolVal (Proxy :: Proxy path)
743+ where p = pack $ symbolVal (Proxy :: Proxy path)
745 hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
745 hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
@@ -789,7 +789,7 @@ instance ( HasClient m api
790-- | Ignore @'Fragment'@ in client functions.
790-- | Ignore @'Fragment'@ in client functions.
791-- See <https://ietf.org/rfc/rfc2616.html#section-15.1.3> for more details.
791-- See <https://ietf.org/rfc/rfc2616.html#section-15.1.3> for more details.
793-- Example:
793-- Example:
795-- > type MyApi = "books" :> Fragment Text :> Get '[JSON] [Book]
795-- > type MyApi = "books" :> Fragment Text :> Get '[JSON] [Book]
@@ -801,12 +801,16 @@ instance ( HasClient m api
801-- > getBooks = client myApi
801-- > getBooks = client myApi
802-- > -- then you can just use "getBooksBy" to query that endpoint.
802-- > -- then you can just use "getBooksBy" to query that endpoint.
803-- > -- 'getBooks' for all books.
803-- > -- 'getBooks' for all books.
804+#ifdef HAS_TYPE_ERROR
804instance (AtLeastOneFragment api, FragmentUnique (Fragment a :> api), HasClient m api
805instance (AtLeastOneFragment api, FragmentUnique (Fragment a :> api), HasClient m api
807+instance ( HasClient m api
805 ) => HasClient m (Fragment a :> api) where
809 ) => HasClient m (Fragment a :> api) where
807 type Client m (Fragment a :> api) = Client m api
811 type Client m (Fragment a :> api) = Client m api
809− clientWithRoute pm _ = clientWithRoute pm (Proxy :: Proxy api)
813+ clientWithRoute pm _ = clientWithRoute pm (Proxy :: Proxy api)
811 hoistClientMonad pm _ = hoistClientMonad pm (Proxy :: Proxy api)
815 hoistClientMonad pm _ = hoistClientMonad pm (Proxy :: Proxy api)
@@ -826,6 +830,7 @@ data AsClientT (m :: * -> *)
826instance GenericMode (AsClientT m) where
830instance GenericMode (AsClientT m) where
827 type AsClientT m :- api = Client m api
831 type AsClientT m :- api = Client m api
833+#if __GLASGOW_HASKELL__ >= 806
830type GClientConstraints api m =
835type GClientConstraints api m =
831 ( GenericServant api (AsClientT m)
836 ( GenericServant api (AsClientT m)
@@ -833,10 +838,10 @@ type GClientConstraints api m =
835class GClient (api :: * -> *) m where
840class GClient (api :: * -> *) m where
836− gClientProof :: Dict (GClientConstraints api m)
841+ proof :: Dict (GClientConstraints api m)
838instance GClientConstraints api m => GClient api m where
843instance GClientConstraints api m => GClient api m where
839− gClientProof = Dict
844+ proof = Dict
842 ( forall n. GClient api n
847 ( forall n. GClient api n
@@ -848,7 +853,7 @@ instance
849 clientWithRoute :: Proxy m -> Proxy (NamedRoutes api) -> Request -> Client m (NamedRoutes api)
854 clientWithRoute :: Proxy m -> Proxy (NamedRoutes api) -> Request -> Client m (NamedRoutes api)
850 clientWithRoute pm _ request =
855 clientWithRoute pm _ request =
851− case gClientProof @api @m of
856+ case proof @api @m of
852 Dict -> fromServant $ clientWithRoute pm (Proxy @(ToServantApi api)) request
857 Dict -> fromServant $ clientWithRoute pm (Proxy @(ToServantApi api)) request
854 hoistClientMonad
859 hoistClientMonad
@@ -859,81 +864,13 @@ instance
859 -> Client ma (NamedRoutes api)
864 -> Client ma (NamedRoutes api)
860 -> Client mb (NamedRoutes api)
865 -> Client mb (NamedRoutes api)
861 hoistClientMonad _ _ nat clientA =
866 hoistClientMonad _ _ nat clientA =
862− case (gClientProof @api @ma, gClientProof @api @mb) of
867+ case (proof @api @ma, proof @api @mb) of
863 (Dict, Dict) ->
868 (Dict, Dict) ->
864 fromServant @api @(AsClientT mb) $
869 fromServant @api @(AsClientT mb) $
865 hoistClientMonad @m @(ToServantApi api) @ma @mb Proxy Proxy nat $
870 hoistClientMonad @m @(ToServantApi api) @ma @mb Proxy Proxy nat $
866 toServant @api @(AsClientT ma) clientA
871 toServant @api @(AsClientT ma) clientA
868−infixl 1 //
873+#endif
871−-- | Helper to make code using records of clients more readable.
873−-- Can be mixed with (/:) for supplying arguments.
878−-- type Api = NamedRoutes RootApi
880−-- data RootApi mode = RootApi
881−-- { subApi :: mode :- NamedRoutes SubApi
883−-- } deriving Generic
885−-- data SubApi mode = SubApi
886−-- { endpoint :: mode :- Get '[JSON] Person
888−-- } deriving Generic
893−-- rootClient :: RootApi (AsClientT ClientM)
894−-- rootClient = client api
896−-- endpointClient :: ClientM Person
897−-- endpointClient = client // subApi // endpoint
899−(//) :: a -> (a -> b) -> b
902−-- | Convenience function for supplying arguments to client functions when
903−-- working with records of clients.
905−-- Intended to be used in conjunction with '(//)'.
910−-- type Api = NamedRoutes RootApi
912−-- data RootApi mode = RootApi
913−-- { subApi :: mode :- Capture "token" String :> NamedRoutes SubApi
914−-- , hello :: mode :- Capture "name" String :> Get '[JSON] String
916−-- } deriving Generic
918−-- data SubApi mode = SubApi
919−-- { endpoint :: mode :- Get '[JSON] Person
921−-- } deriving Generic
926−-- rootClient :: RootApi (AsClientT ClientM)
927−-- rootClient = client api
929−-- hello :: String -> ClientM String
930−-- hello name = rootClient // hello /: name
932−-- endpointClient :: ClientM Person
933−-- endpointClient = client // subApi /: "foobar123" // endpoint
935−(/:) :: (a -> b -> c) -> b -> a -> c
939{- Note [Non-Empty Content Types]
876{- Note [Non-Empty Content Types]
@@ -959,7 +896,7 @@ for empty and one for non-empty lists).
959checkContentTypeHeader :: RunClient m => Response -> m MediaType
896checkContentTypeHeader :: RunClient m => Response -> m MediaType
960checkContentTypeHeader response =
897checkContentTypeHeader response =
961 case lookup "Content-Type" $ toList $ responseHeaders response of
898 case lookup "Content-Type" $ toList $ responseHeaders response of
962− Nothing -> return $ "application" Media.// "octet-stream"
899+ Nothing -> return $ "application"//"octet-stream"
963 Just t -> case parseAccept t of
900 Just t -> case parseAccept t of
964 Nothing -> throwClientError $ InvalidContentTypeHeader response
901 Nothing -> throwClientError $ InvalidContentTypeHeader response
965 Just t' -> return t'
902 Just t' -> return t'
@@ -975,19 +912,3 @@ decodedAs response ct = do
975 Right val -> return val
912 Right val -> return val
977 accept = toList $ contentTypes ct
914 accept = toList $ contentTypes ct
979−-------------------------------------------------------------------------------
980−-- Custom type errors
981−-------------------------------------------------------------------------------
983−-- Erroring instance for HasClient' when a combinator is not fully applied
984−instance (RunClient m, TypeError (PartialApplication HasClient arr)) => HasClient m ((arr :: a -> b) :> sub)
986− type Client m (arr :> sub) = TypeError (PartialApplication HasClient arr)
987− clientWithRoute _ _ _ = error "unreachable"
988− hoistClientMonad _ _ _ _ = error "unreachable"
990−-- Erroring instances for 'HasClient' for unknown API combinators
991−instance {-# OVERLAPPABLE #-} (RunClient m, TypeError (NoInstanceForSub (HasClient m) ty)) => HasClient m (ty :> sub)
993−instance {-# OVERLAPPABLE #-} (RunClient m, TypeError (NoInstanceFor (HasClient m api))) => HasClient m api