@@ -1,4 +1,4 @@
1−{-# LANGUAGE ConstraintKinds #-}
1+{-# LANGUAGE CPP #-}
22{-# LANGUAGE DataKinds #-}
33{-# LANGUAGE FlexibleContexts #-}
44{-# LANGUAGE FlexibleInstances #-}
@@ -6,99 +6,60 @@
66{-# LANGUAGE MultiParamTypeClasses #-}
77{-# LANGUAGE OverloadedStrings #-}
88{-# LANGUAGE PolyKinds #-}
9−{-# LANGUAGE QuantifiedConstraints #-}
109{-# LANGUAGE RankNTypes #-}
1110{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeApplications #-}
1311{-# LANGUAGE TypeFamilies #-}
1412{-# LANGUAGE TypeOperators #-}
1513{-# LANGUAGE UndecidableInstances #-}
1614
17−module Servant.Client.Core.HasClient (
18− clientIn,
19− HasClient (..),
20− EmptyClient (..),
21− AsClientT,
22− (//),
23− (/:),
24− foldMapUnion,
25− matchUnion,
26− ) where
15+#include "overlapping-compat.h"
16+module Servant.Client.Core.Internal.HasClient where
2717
2818import Prelude ()
2919import Prelude.Compat
3020
31−import Control.Arrow
32− (left, (+++))
33−import Control.Monad
34− (unless)
35−import qualified Data.ByteString as BS
36−import qualified Data.ByteString.Lazy as BL
37−import Data.Either
38− (partitionEithers)
39−import Data.Constraint (Dict(..))
21+import Control.Concurrent
22+ (modifyMVar, newMVar)
23+import Control.Monad.IO.Class
24+ (MonadIO (..))
25+import qualified Data.ByteString.Lazy as BL
4026import Data.Foldable
4127 (toList)
4228import Data.List
4329 (foldl')
30+import Data.Proxy
31+ (Proxy (Proxy))
32+import Data.Semigroup
33+ ((<>))
4434import Data.Sequence
4535 (fromList)
46−import qualified Data.Text as T
47−import Network.HTTP.Media
48− (MediaType, matches, parseAccept)
49−import qualified Network.HTTP.Media as Media
50−import qualified Data.Sequence as Seq
51−import Data.SOP.BasicFunctors
52− (I (I), (:.:) (Comp))
53−import Data.SOP.Constraint
54− (All)
55−import Data.SOP.NP
56− (NP (..), cpure_NP)
57−import Data.SOP.NS
58− (NS (S))
5936import Data.String
6037 (fromString)
6138import Data.Text
6239 (Text, pack)
63−import Data.Proxy
64− (Proxy (Proxy))
6540import GHC.TypeLits
66− (KnownNat, KnownSymbol, TypeError, symbolVal)
67−import Network.HTTP.Types
68− (Status)
69−import qualified Network.HTTP.Types as H
41+ (KnownSymbol, symbolVal)
42+import qualified Network.HTTP.Types as H
7043import Servant.API
7144 ((:<|>) ((:<|>)), (:>), AuthProtect, BasicAuth, BasicAuthData,
72− BuildHeadersTo (..), Capture', CaptureAll, Description,
73− EmptyAPI, Fragment, FramingRender (..), FramingUnrender (..),
74− FromSourceIO (..), Header', Headers (..), HttpVersion,
45+ BuildHeadersTo (..), ByteStringParser (..), Capture',
46+ CaptureAll, Description, EmptyAPI, FramingUnrender (..),
47+ FromResultStream (..), Header', Headers (..), HttpVersion,
7548 IsSecure, MimeRender (mimeRender),
76− MimeUnrender (mimeUnrender), NoContent (NoContent),
77− NoContentVerb, QueryFlag, QueryParam', QueryParams, Raw, RawM,
78− ReflectMethod (..), RemoteHost, ReqBody', SBoolI, Stream,
79− StreamBody', Summary, ToHttpApiData, ToSourceIO (..), Vault,
80− Verb, WithNamedContext, WithResource, WithStatus (..), contentType, getHeadersHList,
81− getResponse, toEncodedUrlPiece, toUrlPiece, NamedRoutes)
82−import Servant.API.Generic
83− (GenericMode(..), ToServant, ToServantApi
84− , GenericServant, toServant, fromServant)
49+ MimeUnrender (mimeUnrender), NoContent (NoContent), QueryFlag,
50+ QueryParam', QueryParams, Raw, ReflectMethod (..), RemoteHost,
51+ ReqBody', ResultStream (..), SBoolI, Stream, Summary,
52+ ToHttpApiData, Vault, Verb, WithNamedContext, contentType,
53+ getHeadersHList, getResponse, toQueryParam, toUrlPiece)
8554import Servant.API.ContentTypes
86− (contentTypes, AllMime (allMime), AllMimeUnrender (allMimeUnrender))
87−import Servant.API.Status
88− (statusFromNat)
89−import Servant.API.TypeLevel (FragmentUnique, AtLeastOneFragment)
55+ (contentTypes)
9056import Servant.API.Modifiers
9157 (FoldRequired, RequiredArgument, foldRequiredArgument)
92−import Servant.API.TypeErrors
93−import Servant.API.UVerb
94− (HasStatus, HasStatuses (Statuses, statuses), UVerb, Union, Unique, inject, statusOf, foldMapUnion, matchUnion)
9558
96−import Servant.Client.Core.Auth
97−import Servant.Client.Core.BasicAuth
98−import Servant.Client.Core.ClientError
99−import Servant.Client.Core.Request
100−import Servant.Client.Core.Response
101−import Servant.Client.Core.RunClient
59+import Servant.Client.Core.Internal.Auth
60+import Servant.Client.Core.Internal.BasicAuth
61+import Servant.Client.Core.Internal.Request
62+import Servant.Client.Core.Internal.RunClient
10263
10364-- * Accessing APIs as a Client
10465
@@ -208,7 +169,7 @@ instance (KnownSymbol capture, ToHttpApiData a, HasClient m api)
208169 clientWithRoute pm (Proxy :: Proxy api)
209170 (appendToPath p req)
210171
211− where p = toEncodedUrlPiece val
172+ where p = (toUrlPiece val)
212173
213174 hoistClientMonad pm _ f cl = \a ->
214175 hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
@@ -243,19 +204,18 @@ instance (KnownSymbol capture, ToHttpApiData a, HasClient m sublayout)
243204 clientWithRoute pm (Proxy :: Proxy sublayout)
244205 (foldl' (flip appendToPath) req ps)
245206
246− where ps = map toEncodedUrlPiece vals
207+ where ps = map (toUrlPiece) vals
247208
248209 hoistClientMonad pm _ f cl = \as ->
249210 hoistClientMonad pm (Proxy :: Proxy sublayout) f (cl as)
250211
251−instance {-# OVERLAPPABLE #-}
212+instance OVERLAPPABLE_
252213 -- Note [Non-Empty Content Types]
253214 ( RunClient m, MimeUnrender ct a, ReflectMethod method, cts' ~ (ct ': cts)
254− , KnownNat status
255215 ) => HasClient m (Verb method status cts' a) where
256216 type Client m (Verb method status cts' a) = m a
257217 clientWithRoute _pm Proxy req = do
258− response <- runRequestAcceptStatus (Just [status]) req
218+ response <- runRequest req
259219 { requestAccept = fromList $ toList accept
260220 , requestMethod = method
261221 }
@@ -263,27 +223,14 @@ instance {-# OVERLAPPABLE #-}
263223 where
264224 accept = contentTypes (Proxy :: Proxy ct)
265225 method = reflectMethod (Proxy :: Proxy method)
266− status = statusFromNat (Proxy :: Proxy status)
267226
268227 hoistClientMonad _ _ f ma = f ma
269228
270−instance {-# OVERLAPPING #-}
271− ( RunClient m, ReflectMethod method, KnownNat status
229+instance OVERLAPPING_
230+ ( RunClient m, ReflectMethod method
272231 ) => HasClient m (Verb method status cts NoContent) where
273232 type Client m (Verb method status cts NoContent)
274233 = m NoContent
275− clientWithRoute _pm Proxy req = do
276− _response <- runRequestAcceptStatus (Just [status]) req { requestMethod = method }
277− return NoContent
278− where method = reflectMethod (Proxy :: Proxy method)
279− status = statusFromNat (Proxy :: Proxy status)
280−
281− hoistClientMonad _ _ f ma = f ma
282−
283−instance (RunClient m, ReflectMethod method) =>
284− HasClient m (NoContentVerb method) where
285− type Client m (NoContentVerb method)
286− = m NoContent
287234 clientWithRoute _pm Proxy req = do
288235 _response <- runRequest req { requestMethod = method }
289236 return NoContent
@@ -291,175 +238,93 @@ instance (RunClient m, ReflectMethod method) =>
291238
292239 hoistClientMonad _ _ f ma = f ma
293240
294−instance {-# OVERLAPPING #-}
241+instance OVERLAPPING_
295242 -- Note [Non-Empty Content Types]
296− ( RunClient m, MimeUnrender ct a, BuildHeadersTo ls, KnownNat status
243+ ( RunClient m, MimeUnrender ct a, BuildHeadersTo ls
297244 , ReflectMethod method, cts' ~ (ct ': cts)
298245 ) => HasClient m (Verb method status cts' (Headers ls a)) where
299246 type Client m (Verb method status cts' (Headers ls a))
300247 = m (Headers ls a)
301248 clientWithRoute _pm Proxy req = do
302− response <- runRequestAcceptStatus (Just [status]) req
249+ response <- runRequest req
303250 { requestMethod = method
304251 , requestAccept = fromList $ toList accept
305252 }
306− val <- response `decodedAs` (Proxy :: Proxy ct)
307− return $ Headers { getResponse = val
308− , getHeadersHList = buildHeadersTo . toList $ responseHeaders response
309− }
310− where
311− method = reflectMethod (Proxy :: Proxy method)
312− accept = contentTypes (Proxy :: Proxy ct)
313− status = statusFromNat (Proxy :: Proxy status)
253+ case mimeUnrender (Proxy :: Proxy ct) $ responseBody response of
254+ Left err -> throwServantError $ DecodeFailure (pack err) response
255+ Right val -> return $ Headers
256+ { getResponse = val
257+ , getHeadersHList = buildHeadersTo . toList $ responseHeaders response
258+ }
259+ where method = reflectMethod (Proxy :: Proxy method)
260+ accept = contentTypes (Proxy :: Proxy ct)
314261
315262 hoistClientMonad _ _ f ma = f ma
316263
317−instance {-# OVERLAPPING #-}
318− ( RunClient m, BuildHeadersTo ls, ReflectMethod method, KnownNat status
264+instance OVERLAPPING_
265+ ( RunClient m, BuildHeadersTo ls, ReflectMethod method
319266 ) => HasClient m (Verb method status cts (Headers ls NoContent)) where
320267 type Client m (Verb method status cts (Headers ls NoContent))
321268 = m (Headers ls NoContent)
322269 clientWithRoute _pm Proxy req = do
323− response <- runRequestAcceptStatus (Just [status]) req { requestMethod = method }
270+ let method = reflectMethod (Proxy :: Proxy method)
271+ response <- runRequest req { requestMethod = method }
324272 return $ Headers { getResponse = NoContent
325273 , getHeadersHList = buildHeadersTo . toList $ responseHeaders response
326274 }
327− where
328− method = reflectMethod (Proxy :: Proxy method)
329− status = statusFromNat (Proxy :: Proxy status)
330275
331276 hoistClientMonad _ _ f ma = f ma
332277
333−data ClientParseError = ClientParseError MediaType String | ClientStatusMismatch | ClientNoMatchingStatus
334− deriving (Eq, Show)
335−
336−class UnrenderResponse (cts :: [*]) (a :: *) where
337− unrenderResponse :: Seq.Seq H.Header -> BL.ByteString -> Proxy cts
338− -> [Either (MediaType, String) a]
278+instance OVERLAPPABLE_
279+ ( RunClient m, MonadIO m, MimeUnrender ct a, ReflectMethod method,
280+ FramingUnrender framing a, FromResultStream a b
281+ ) => HasClient m (Stream method status framing ct b) where
339282
340−instance {-# OVERLAPPABLE #-} AllMimeUnrender cts a => UnrenderResponse cts a where
341− unrenderResponse _ body = map parse . allMimeUnrender
342− where parse (mediaType, parser) = left ((,) mediaType) (parser body)
343−
344−instance {-# OVERLAPPING #-} forall cts a h . (UnrenderResponse cts a, BuildHeadersTo h)
345− => UnrenderResponse cts (Headers h a) where
346− unrenderResponse hs body = (map . fmap) setHeaders . unrenderResponse hs body
347− where
348− setHeaders :: a -> Headers h a
349− setHeaders x = Headers x (buildHeadersTo (toList hs))
350−
351−instance {-# OVERLAPPING #-} UnrenderResponse cts a
352− => UnrenderResponse cts (WithStatus n a) where
353− unrenderResponse hs body = (map . fmap) WithStatus . unrenderResponse hs body
354−
355−instance {-# OVERLAPPING #-}
356− ( RunClient m,
357− contentTypes ~ (contentType ': otherContentTypes),
358− -- ('otherContentTypes' should be '_', but even -XPartialTypeSignatures does not seem
359− -- allow this in instance types as of 8.8.3.)
360− as ~ (a ': as'),
361− AllMime contentTypes,
362− ReflectMethod method,
363− All (UnrenderResponse contentTypes) as,
364− All HasStatus as, HasStatuses as',
365− Unique (Statuses as)
366− ) =>
367− HasClient m (UVerb method contentTypes as)
368− where
369− type Client m (UVerb method contentTypes as) = m (Union as)
370−
371− clientWithRoute _ _ request = do
372− let accept = Seq.fromList . allMime $ Proxy @contentTypes
373− -- offering to accept all mime types listed in the api gives best compatibility. eg.,
374− -- we might not own the server implementation, and the server may choose to support
375− -- only part of the api.
376−
377− method = reflectMethod $ Proxy @method
378− acceptStatus = statuses (Proxy @as)
379− response <- runRequestAcceptStatus (Just acceptStatus) request {requestMethod = method, requestAccept = accept}
380− responseContentType <- checkContentTypeHeader response
381− unless (any (matches responseContentType) accept) $ do
382− throwClientError $ UnsupportedContentType responseContentType response
383−
384− let status = responseStatusCode response
385− body = responseBody response
386− headers = responseHeaders response
387− res = tryParsers status $ mimeUnrenders (Proxy @contentTypes) headers body
388− case res of
389− Left errors -> throwClientError $ DecodeFailure (T.pack (show errors)) response
390− Right x -> return x
391− where
392− -- | Given a list of parsers of 'mkres', returns the first one that succeeds and all the
393− -- failures it encountered along the way
394− -- TODO; better name, rewrite haddocs.
395− tryParsers :: forall xs. All HasStatus xs => Status -> NP ([] :.: Either (MediaType, String)) xs -> Either [ClientParseError] (Union xs)
396− tryParsers _ Nil = Left [ClientNoMatchingStatus]
397− tryParsers status (Comp x :* xs)
398− | status == statusOf (Comp x) =
399− case partitionEithers x of
400− (err', []) -> (map (uncurry ClientParseError) err' ++) +++ S $ tryParsers status xs
401− (_, (res : _)) -> Right . inject . I $ res
402− | otherwise = -- no reason to parse in the first place. This ain't the one we're looking for
403− (ClientStatusMismatch :) +++ S $ tryParsers status xs
404−
405− -- | Given a list of types, parses the given response body as each type
406− mimeUnrenders ::
407− forall cts xs.
408− All (UnrenderResponse cts) xs =>
409− Proxy cts ->
410− Seq.Seq H.Header ->
411− BL.ByteString ->
412− NP ([] :.: Either (MediaType, String)) xs
413− mimeUnrenders ctp headers body = cpure_NP
414− (Proxy @(UnrenderResponse cts))
415− (Comp . unrenderResponse headers body $ ctp)
416−
417− hoistClientMonad _ _ nt s = nt s
418−
419−instance {-# OVERLAPPABLE #-}
420− ( RunStreamingClient m, MimeUnrender ct chunk, ReflectMethod method,
421− FramingUnrender framing, FromSourceIO chunk a
422− ) => HasClient m (Stream method status framing ct a) where
423−
424− type Client m (Stream method status framing ct a) = m a
283+ type Client m (Stream method status framing ct b) = m b
425284
426− hoistClientMonad _ _ f ma = f ma
427−
428− clientWithRoute _pm Proxy req = withStreamingRequest req' $ \gres -> do
429− let mimeUnrender' = mimeUnrender (Proxy :: Proxy ct) :: BL.ByteString -> Either String chunk
430− framingUnrender' = framingUnrender (Proxy :: Proxy framing) mimeUnrender'
431− return $ fromSourceIO $ framingUnrender' $ responseBody gres
432− where
433− req' = req
434− { requestAccept = fromList [contentType (Proxy :: Proxy ct)]
435− , requestMethod = reflectMethod (Proxy :: Proxy method)
436− }
437−
438−instance {-# OVERLAPPING #-}
439− ( RunStreamingClient m, MimeUnrender ct chunk, ReflectMethod method,
440− FramingUnrender framing, FromSourceIO chunk a,
441− BuildHeadersTo hs
442− ) => HasClient m (Stream method status framing ct (Headers hs a)) where
443−
444− type Client m (Stream method status framing ct (Headers hs a)) = m (Headers hs a)
285+ clientWithRoute _pm Proxy req = do
286+ sresp <- streamingRequest req
287+ { requestAccept = fromList [contentType (Proxy :: Proxy ct)]
288+ , requestMethod = reflectMethod (Proxy :: Proxy method)
289+ }
290+ liftIO $ fromResultStream $ ResultStream $ \k ->
291+ runStreamingResponse sresp $ \gres -> do
292+ let reader = responseBody gres
293+ let unrender = unrenderFrames (Proxy :: Proxy framing) (Proxy :: Proxy a)
294+ loop bs = do
295+ res <- BL.fromStrict <$> reader
296+ if BL.null res
297+ then return $ parseEOF unrender res
298+ else let sofar = (bs <> res)
299+ in case parseIncremental unrender sofar of
300+ Just x -> return x
301+ Nothing -> loop sofar
302+ (frameParser, remainder) <- loop BL.empty
303+ state <- newMVar remainder
304+ let frameLoop bs = do
305+ res <- BL.fromStrict <$> reader
306+ let addIsEmptyInfo (a, r) = (r, (a, BL.null r && BL.null res))
307+ if BL.null res
308+ then if BL.null bs
309+ then return ("", (Right "", True))
310+ else return . addIsEmptyInfo $ parseEOF frameParser bs
311+ else let sofar = (bs <> res)
312+ in case parseIncremental frameParser sofar of
313+ Just x -> return $ addIsEmptyInfo x
314+ Nothing -> frameLoop sofar
315+
316+ go = processResult <$> modifyMVar state frameLoop
317+ processResult (Right bs,isDone) =
318+ if BL.null bs && isDone
319+ then Nothing
320+ else Just $ case mimeUnrender (Proxy :: Proxy ct) bs :: Either String a of
321+ Left err -> Left err
322+ Right x -> Right x
323+ processResult (Left err, _) = Just (Left err)
324+ k go
445325
446326 hoistClientMonad _ _ f ma = f ma
447327
448− clientWithRoute _pm Proxy req = withStreamingRequest req' $ \gres -> do
449− let mimeUnrender' = mimeUnrender (Proxy :: Proxy ct) :: BL.ByteString -> Either String chunk
450− framingUnrender' = framingUnrender (Proxy :: Proxy framing) mimeUnrender'
451− val = fromSourceIO $ framingUnrender' $ responseBody gres
452− return $ Headers
453− { getResponse = val
454− , getHeadersHList = buildHeadersTo . toList $ responseHeaders gres
455− }
456−
457− where
458− req' = req
459− { requestAccept = fromList [contentType (Proxy :: Proxy ct)]
460− , requestMethod = reflectMethod (Proxy :: Proxy method)
461− }
462−
463328-- | If you use a 'Header' in one of your endpoints in your API,
464329-- the corresponding querying function will automatically take
465330-- an additional argument of the type specified by your 'Header',
@@ -569,7 +434,7 @@ instance (KnownSymbol sym, ToHttpApiData a, HasClient m api, SBoolI (FoldRequire
569434 (Proxy :: Proxy mods) add (maybe req add) mparam
570435 where
571436 add :: a -> Request
572− add param = appendToQueryString pname (Just $ encodeQueryParamValue param) req
437+ add param = appendToQueryString pname (Just $ toQueryParam param) req
573438
574439 pname :: Text
575440 pname = pack $ symbolVal (Proxy :: Proxy sym)
@@ -618,7 +483,7 @@ instance (KnownSymbol sym, ToHttpApiData a, HasClient m api)
618483 )
619484
620485 where pname = pack $ symbolVal (Proxy :: Proxy sym)
621− paramlist' = map (Just . encodeQueryParamValue) paramlist
486+ paramlist' = map (Just . toQueryParam) paramlist
622487
623488 hoistClientMonad pm _ f cl = \as ->
624489 hoistClientMonad pm (Proxy :: Proxy api) f (cl as)
@@ -674,16 +539,6 @@ instance RunClient m => HasClient m Raw where
674539
675540 hoistClientMonad _ _ f cl = \meth -> f (cl meth)
676541
677−instance RunClient m => HasClient m RawM where
678− type Client m RawM
679− = H.Method -> m Response
680−
681− clientWithRoute :: Proxy m -> Proxy RawM -> Request -> Client m RawM
682− clientWithRoute _pm Proxy req httpMethod = do
683− runRequest req { requestMethod = httpMethod }
684−
685− hoistClientMonad _ _ f cl = \meth -> f (cl meth)
686−
687542-- | If you use a 'ReqBody' in one of your endpoints in your API,
688543-- the corresponding querying function will automatically take
689544-- an additional argument of the type specified by your 'ReqBody'.
@@ -720,28 +575,6 @@ instance (MimeRender ct a, HasClient m api)
720575 hoistClientMonad pm _ f cl = \a ->
721576 hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
722577
723−instance
724− ( HasClient m api, MimeRender ctype chunk, FramingRender framing, ToSourceIO chunk a
725− ) => HasClient m (StreamBody' mods framing ctype a :> api)
726− where
727−
728− type Client m (StreamBody' mods framing ctype a :> api) = a -> Client m api
729−
730− hoistClientMonad pm _ f cl = \a ->
731− hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
732−
733− clientWithRoute pm Proxy req body
734− = clientWithRoute pm (Proxy :: Proxy api)
735− $ setRequestBody (RequestBodySource sourceIO) (contentType ctypeP) req
736− where
737− ctypeP = Proxy :: Proxy ctype
738− framingP = Proxy :: Proxy framing
739−
740− sourceIO = framingRender
741− framingP
742− (mimeRender ctypeP :: chunk -> BL.ByteString)
743− (toSourceIO body)
744−
745578-- | Make the querying function append @path@ to the request path.
746579instance (KnownSymbol path, HasClient m api) => HasClient m (path :> api) where
747580 type Client m (path :> api) = Client m api
@@ -750,7 +583,7 @@ instance (KnownSymbol path, HasClient m api) => HasClient m (path :> api) where
750583 clientWithRoute pm (Proxy :: Proxy api)
751584 (appendToPath p req)
752585
753− where p = toEncodedUrlPiece $ pack $ symbolVal (Proxy :: Proxy path)
586+ where p = pack $ symbolVal (Proxy :: Proxy path)
754587
755588 hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
756589
@@ -786,14 +619,6 @@ instance HasClient m subapi =>
786619
787620 hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy subapi) f cl
788621
789−instance HasClient m subapi =>
790− HasClient m (WithResource res :> subapi) where
791−
792− type Client m (WithResource res :> subapi) = Client m subapi
793− clientWithRoute pm Proxy = clientWithRoute pm (Proxy :: Proxy subapi)
794−
795− hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy subapi) f cl
796−
797622instance ( HasClient m api
798623 ) => HasClient m (AuthProtect tag :> api) where
799624 type Client m (AuthProtect tag :> api)
@@ -805,29 +630,6 @@ instance ( HasClient m api
805630 hoistClientMonad pm _ f cl = \authreq ->
806631 hoistClientMonad pm (Proxy :: Proxy api) f (cl authreq)
807632
808−-- | Ignore @'Fragment'@ in client functions.
809−-- See <https://ietf.org/rfc/rfc2616.html#section-15.1.3> for more details.
810−--
811−-- Example:
812−--
813−-- > type MyApi = "books" :> Fragment Text :> Get '[JSON] [Book]
814−-- >
815−-- > myApi :: Proxy MyApi
816−-- > myApi = Proxy
817−-- >
818−-- > getBooks :: ClientM [Book]
819−-- > getBooks = client myApi
820−-- > -- then you can just use "getBooksBy" to query that endpoint.
821−-- > -- 'getBooks' for all books.
822−instance (AtLeastOneFragment api, FragmentUnique (Fragment a :> api), HasClient m api
823− ) => HasClient m (Fragment a :> api) where
824−
825− type Client m (Fragment a :> api) = Client m api
826−
827− clientWithRoute pm _ = clientWithRoute pm (Proxy :: Proxy api)
828−
829− hoistClientMonad pm _ = hoistClientMonad pm (Proxy :: Proxy api)
830−
831633-- * Basic Authentication
832634
833635instance HasClient m api => HasClient m (BasicAuth realm usr :> api) where
@@ -839,120 +641,6 @@ instance HasClient m api => HasClient m (BasicAuth realm usr :> api) where
839641 hoistClientMonad pm _ f cl = \bauth ->
840642 hoistClientMonad pm (Proxy :: Proxy api) f (cl bauth)
841643
842−-- | A type that specifies that an API record contains a client implementation.
843−data AsClientT (m :: * -> *)
844−instance GenericMode (AsClientT m) where
845− type AsClientT m :- api = Client m api
846−
847−
848−type GClientConstraints api m =
849− ( GenericServant api (AsClientT m)
850− , Client m (ToServantApi api) ~ ToServant api (AsClientT m)
851− )
852−
853−class GClient (api :: * -> *) m where
854− gClientProof :: Dict (GClientConstraints api m)
855−
856−instance GClientConstraints api m => GClient api m where
857− gClientProof = Dict
858−
859−instance
860− ( forall n. GClient api n
861− , HasClient m (ToServantApi api)
862− , RunClient m
863− )
864− => HasClient m (NamedRoutes api) where
865− type Client m (NamedRoutes api) = api (AsClientT m)
866−
867− clientWithRoute :: Proxy m -> Proxy (NamedRoutes api) -> Request -> Client m (NamedRoutes api)
868− clientWithRoute pm _ request =
869− case gClientProof @api @m of
870− Dict -> fromServant $ clientWithRoute pm (Proxy @(ToServantApi api)) request
871−
872− hoistClientMonad
873− :: forall ma mb.
874− Proxy m
875− -> Proxy (NamedRoutes api)
876− -> (forall x. ma x -> mb x)
877− -> Client ma (NamedRoutes api)
878− -> Client mb (NamedRoutes api)
879− hoistClientMonad _ _ nat clientA =
880− case (gClientProof @api @ma, gClientProof @api @mb) of
881− (Dict, Dict) ->
882− fromServant @api @(AsClientT mb) $
883− hoistClientMonad @m @(ToServantApi api) @ma @mb Proxy Proxy nat $
884− toServant @api @(AsClientT ma) clientA
885−
886−infixl 1 //
887−infixl 2 /:
888−
889−-- | Helper to make code using records of clients more readable.
890−--
891−-- Can be mixed with (/:) for supplying arguments.
892−--
893−-- Example:
894−--
895−-- @
896−-- type Api = NamedRoutes RootApi
897−--
898−-- data RootApi mode = RootApi
899−-- { subApi :: mode :- NamedRoutes SubApi
900−-- , …
901−-- } deriving Generic
902−--
903−-- data SubApi mode = SubApi
904−-- { endpoint :: mode :- Get '[JSON] Person
905−-- , …
906−-- } deriving Generic
907−--
908−-- api :: Proxy API
909−-- api = Proxy
910−--
911−-- rootClient :: RootApi (AsClientT ClientM)
912−-- rootClient = client api
913−--
914−-- endpointClient :: ClientM Person
915−-- endpointClient = client \/\/ subApi \/\/ endpoint
916−-- @
917−(//) :: a -> (a -> b) -> b
918−x // f = f x
919−
920−-- | Convenience function for supplying arguments to client functions when
921−-- working with records of clients.
922−--
923−-- Intended to be used in conjunction with '(//)'.
924−--
925−-- Example:
926−--
927−-- @
928−-- type Api = NamedRoutes RootApi
929−--
930−-- data RootApi mode = RootApi
931−-- { subApi :: mode :- Capture "token" String :> NamedRoutes SubApi
932−-- , hello :: mode :- Capture "name" String :> Get '[JSON] String
933−-- , …
934−-- } deriving Generic
935−--
936−-- data SubApi mode = SubApi
937−-- { endpoint :: mode :- Get '[JSON] Person
938−-- , …
939−-- } deriving Generic
940−--
941−-- api :: Proxy API
942−-- api = Proxy
943−--
944−-- rootClient :: RootApi (AsClientT ClientM)
945−-- rootClient = client api
946−--
947−-- hello :: String -> ClientM String
948−-- hello name = rootClient \/\/ hello \/: name
949−--
950−-- endpointClient :: ClientM Person
951−-- endpointClient = client \/\/ subApi \/: "foobar123" \/\/ endpoint
952−-- @
953−(/:) :: (a -> b -> c) -> b -> a -> c
954−(/:) = flip
955−
956644
957645{- Note [Non-Empty Content Types]
958646~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -969,43 +657,3 @@ non-empty lists, but is otherwise more specific, no instance will be overall
969657more specific. This in turn generally means adding yet another instance (one
970658for empty and one for non-empty lists).
971659-}
972−
973−-------------------------------------------------------------------------------
974−-- helpers
975−-------------------------------------------------------------------------------
976−
977−checkContentTypeHeader :: RunClient m => Response -> m MediaType
978−checkContentTypeHeader response =
979− case lookup "Content-Type" $ toList $ responseHeaders response of
980− Nothing -> return $ "application" Media.// "octet-stream"
981− Just t -> case parseAccept t of
982− Nothing -> throwClientError $ InvalidContentTypeHeader response
983− Just t' -> return t'
984−
985−decodedAs :: forall ct a m. (MimeUnrender ct a, RunClient m)
986− => Response -> Proxy ct -> m a
987−decodedAs response ct = do
988− responseContentType <- checkContentTypeHeader response
989− unless (any (matches responseContentType) accept) $
990− throwClientError $ UnsupportedContentType responseContentType response
991− case mimeUnrender ct $ responseBody response of
992− Left err -> throwClientError $ DecodeFailure (T.pack err) response
993− Right val -> return val
994− where
995− accept = toList $ contentTypes ct
996−
997−-------------------------------------------------------------------------------
998−-- Custom type errors
999−-------------------------------------------------------------------------------
1000−
1001−-- Erroring instance for HasClient' when a combinator is not fully applied
1002−instance (RunClient m, TypeError (PartialApplication HasClient arr)) => HasClient m ((arr :: a -> b) :> sub)
1003− where
1004− type Client m (arr :> sub) = TypeError (PartialApplication HasClient arr)
1005− clientWithRoute _ _ _ = error "unreachable"
1006− hoistClientMonad _ _ _ _ = error "unreachable"
1007−
1008−-- Erroring instances for 'HasClient' for unknown API combinators
1009−instance {-# OVERLAPPABLE #-} (RunClient m, TypeError (NoInstanceForSub (HasClient m) ty)) => HasClient m (ty :> sub)
1010−
1011−instance {-# OVERLAPPABLE #-} (RunClient m, TypeError (NoInstanceFor (HasClient m api))) => HasClient m api