@@ -0,0 +1,305 @@
1+{-# LANGUAGE InstanceSigs #-}
2+{-# LANGUAGE TypeFamilies #-}
3+{-# LANGUAGE TypeOperators #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE OverloadedStrings #-}
6+{-# LANGUAGE ScopedTypeVariables #-}
7+-- | This module provides 'client' which can automatically generate
8+-- querying functions for each endpoint just from the type representing your
9+-- API.
10+module Servant.Client
11+ ( client
12+ , HasClient(..)
13+ , module Servant.Common.BaseUrl
14+ ) where
15+
16+import Control.Monad.Trans.Either
17+import Data.Aeson
18+import Data.ByteString.Lazy (ByteString)
19+import Data.List
20+import Data.Proxy
21+import Data.String.Conversions
22+import Data.Text (unpack)
23+import GHC.TypeLits
24+import Network.HTTP.Types
25+import Servant.API
26+import Servant.Common.BaseUrl
27+import Servant.Common.Req
28+import Servant.Common.Text
29+
30+-- * Accessing APIs as a Client
31+
32+-- | 'client' allows you to produce operations to query an API from a client.
33+--
34+-- > type MyApi = "books" :> Get [Book] -- GET /books
35+-- > :<|> "books" :> ReqBody Book :> Post Book -- POST /books
36+-- >
37+-- > myApi :: Proxy MyApi
38+-- > myApi = Proxy
39+-- >
40+-- > getAllBooks :: BaseUrl -> EitherT String IO [Book]
41+-- > postNewBook :: Book -> BaseUrl -> EitherT String IO Book
42+-- > (getAllBooks :<|> postNewBook) = client myApi
43+client :: HasClient layout => Proxy layout -> Client layout
44+client p = clientWithRoute p defReq
45+
46+-- | This class lets us define how each API combinator
47+-- influences the creation of an HTTP request. Use 'client'
48+-- directly, this class implements the client-side
49+-- behavior of each combinator but you don't have to worry about it.
50+class HasClient layout where
51+ type Client layout :: *
52+ clientWithRoute :: Proxy layout -> Req -> Client layout
53+
54+-- | A client querying function for @a ':<|>' b@ will actually hand you
55+-- one function for querying @a@ and another one for querying @b@,
56+-- stitching them together with ':<|>', which really is just like a pair.
57+--
58+-- > type MyApi = "books" :> Get [Book] -- GET /books
59+-- > :<|> "books" :> ReqBody Book :> Post Book -- POST /books
60+-- >
61+-- > myApi :: Proxy MyApi
62+-- > myApi = Proxy
63+-- >
64+-- > getAllBooks :: BaseUrl -> EitherT String IO [Book]
65+-- > postNewBook :: Book -> BaseUrl -> EitherT String IO Book
66+-- > (getAllBooks :<|> postNewBook) = client myApi
67+instance (HasClient a, HasClient b) => HasClient (a :<|> b) where
68+ type Client (a :<|> b) = Client a :<|> Client b
69+ clientWithRoute Proxy req =
70+ clientWithRoute (Proxy :: Proxy a) req :<|>
71+ clientWithRoute (Proxy :: Proxy b) req
72+
73+-- | If you use a 'Capture' in one of your endpoints in your API,
74+-- the corresponding querying function will automatically take
75+-- an additional argument of the type specified by your 'Capture'.
76+-- That function will take care of inserting a textual representation
77+-- of this value at the right place in the request path.
78+--
79+-- You can control how values for this type are turned into
80+-- text by specifying a 'ToText' instance for your type.
81+--
82+-- Example:
83+--
84+-- > type MyApi = "books" :> Capture "isbn" Text :> Get Book
85+-- >
86+-- > myApi :: Proxy MyApi
87+-- > myApi = Proxy
88+-- >
89+-- > getBook :: Text -> BaseUrl -> EitherT String IO Book
90+-- > getBook = client myApi
91+-- > -- then you can just use "getBook" to query that endpoint
92+instance (KnownSymbol capture, ToText a, HasClient sublayout)
93+ => HasClient (Capture capture a :> sublayout) where
94+
95+ type Client (Capture capture a :> sublayout) =
96+ a -> Client sublayout
97+
98+ clientWithRoute Proxy req val =
99+ clientWithRoute (Proxy :: Proxy sublayout) $
100+ appendToPath p req
101+
102+ where p = unpack (toText val)
103+
104+-- | If you have a 'Delete' endpoint in your API, the client
105+-- side querying function that is created when calling 'client'
106+-- will just require an argument that specifies the scheme, host
107+-- and port to send the request to.
108+instance HasClient Delete where
109+ type Client Delete = BaseUrl -> EitherT String IO ()
110+
111+ clientWithRoute Proxy req host =
112+ performRequestJSON methodDelete req 204 host
113+
114+-- | If you have a 'Get' endpoint in your API, the client
115+-- side querying function that is created when calling 'client'
116+-- will just require an argument that specifies the scheme, host
117+-- and port to send the request to.
118+instance FromJSON result => HasClient (Get result) where
119+ type Client (Get result) = BaseUrl -> EitherT String IO result
120+ clientWithRoute Proxy req host =
121+ performRequestJSON methodGet req 200 host
122+
123+-- | If you have a 'Post' endpoint in your API, the client
124+-- side querying function that is created when calling 'client'
125+-- will just require an argument that specifies the scheme, host
126+-- and port to send the request to.
127+instance FromJSON a => HasClient (Post a) where
128+ type Client (Post a) = BaseUrl -> EitherT String IO a
129+
130+ clientWithRoute Proxy req uri =
131+ performRequestJSON methodPost req 201 uri
132+
133+-- | If you have a 'Put' endpoint in your API, the client
134+-- side querying function that is created when calling 'client'
135+-- will just require an argument that specifies the scheme, host
136+-- and port to send the request to.
137+instance FromJSON a => HasClient (Put a) where
138+ type Client (Put a) = BaseUrl -> EitherT String IO a
139+
140+ clientWithRoute Proxy req host =
141+ performRequestJSON methodPut req 200 host
142+
143+-- | If you use a 'QueryParam' in one of your endpoints in your API,
144+-- the corresponding querying function will automatically take
145+-- an additional argument of the type specified by your 'QueryParam',
146+-- enclosed in Maybe.
147+--
148+-- If you give Nothing, nothing will be added to the query string.
149+--
150+-- If you give a non-'Nothing' value, this function will take care
151+-- of inserting a textual representation of this value in the query string.
152+--
153+-- You can control how values for your type are turned into
154+-- text by specifying a 'ToText' instance for your type.
155+--
156+-- Example:
157+--
158+-- > type MyApi = "books" :> QueryParam "author" Text :> Get [Book]
159+-- >
160+-- > myApi :: Proxy MyApi
161+-- > myApi = Proxy
162+-- >
163+-- > getBooksBy :: Maybe Text -> BaseUrl -> EitherT String IO [Book]
164+-- > getBooksBy = client myApi
165+-- > -- then you can just use "getBooksBy" to query that endpoint.
166+-- > -- 'getBooksBy Nothing' for all books
167+-- > -- 'getBooksBy (Just "Isaac Asimov")' to get all books by Isaac Asimov
168+instance (KnownSymbol sym, ToText a, HasClient sublayout)
169+ => HasClient (QueryParam sym a :> sublayout) where
170+
171+ type Client (QueryParam sym a :> sublayout) =
172+ Maybe a -> Client sublayout
173+
174+ -- if mparam = Nothing, we don't add it to the query string
175+ clientWithRoute Proxy req mparam =
176+ clientWithRoute (Proxy :: Proxy sublayout) $
177+ appendToQueryString pname mparamText req
178+
179+ where pname = cs pname'
180+ pname' = symbolVal (Proxy :: Proxy sym)
181+ mparamText = fmap toText mparam
182+
183+-- | If you use a 'QueryParams' in one of your endpoints in your API,
184+-- the corresponding querying function will automatically take
185+-- an additional argument, a list of values of the type specified
186+-- by your 'QueryParams'.
187+--
188+-- If you give an empty list, nothing will be added to the query string.
189+--
190+-- Otherwise, this function will take care
191+-- of inserting a textual representation of your values in the query string,
192+-- under the same query string parameter name.
193+--
194+-- You can control how values for your type are turned into
195+-- text by specifying a 'ToText' instance for your type.
196+--
197+-- Example:
198+--
199+-- > type MyApi = "books" :> QueryParams "authors" Text :> Get [Book]
200+-- >
201+-- > myApi :: Proxy MyApi
202+-- > myApi = Proxy
203+-- >
204+-- > getBooksBy :: [Text] -> BaseUrl -> EitherT String IO [Book]
205+-- > getBooksBy = client myApi
206+-- > -- then you can just use "getBooksBy" to query that endpoint.
207+-- > -- 'getBooksBy []' for all books
208+-- > -- 'getBooksBy ["Isaac Asimov", "Robert A. Heinlein"]'
209+-- > -- to get all books by Asimov and Heinlein
210+instance (KnownSymbol sym, ToText a, HasClient sublayout)
211+ => HasClient (QueryParams sym a :> sublayout) where
212+
213+ type Client (QueryParams sym a :> sublayout) =
214+ [a] -> Client sublayout
215+
216+ clientWithRoute Proxy req paramlist =
217+ clientWithRoute (Proxy :: Proxy sublayout) $
218+ foldl' (\ value req' -> appendToQueryString pname req' value) req paramlist'
219+
220+ where pname = cs pname'
221+ pname' = symbolVal (Proxy :: Proxy sym)
222+ paramlist' = map (Just . toText) paramlist
223+
224+-- | If you use a 'QueryFlag' in one of your endpoints in your API,
225+-- the corresponding querying function will automatically take
226+-- an additional 'Bool' argument.
227+--
228+-- If you give 'False', nothing will be added to the query string.
229+--
230+-- Otherwise, this function will insert a value-less query string
231+-- parameter under the name associated to your 'QueryFlag'.
232+--
233+-- Example:
234+--
235+-- > type MyApi = "books" :> QueryFlag "published" :> Get [Book]
236+-- >
237+-- > myApi :: Proxy MyApi
238+-- > myApi = Proxy
239+-- >
240+-- > getBooks :: Bool -> BaseUrl -> EitherT String IO [Book]
241+-- > getBooks = client myApi
242+-- > -- then you can just use "getBooks" to query that endpoint.
243+-- > -- 'getBooksBy False' for all books
244+-- > -- 'getBooksBy True' to only get _already published_ books
245+instance (KnownSymbol sym, HasClient sublayout)
246+ => HasClient (QueryFlag sym :> sublayout) where
247+
248+ type Client (QueryFlag sym :> sublayout) =
249+ Bool -> Client sublayout
250+
251+ clientWithRoute Proxy req flag =
252+ clientWithRoute (Proxy :: Proxy sublayout) $
253+ if flag
254+ then appendToQueryString paramname Nothing req
255+ else req
256+
257+ where paramname = cs $ symbolVal (Proxy :: Proxy sym)
258+
259+-- | Pick a 'Method' and specify where the server you want to query is. You get
260+-- back the status code and the response body as a 'ByteString'.
261+instance HasClient Raw where
262+ type Client Raw = Method -> BaseUrl -> EitherT String IO (Int, ByteString)
263+
264+ clientWithRoute :: Proxy Raw -> Req -> Client Raw
265+ clientWithRoute Proxy req httpMethod host =
266+ performRequest httpMethod req (const True) host
267+
268+-- | If you use a 'ReqBody' in one of your endpoints in your API,
269+-- the corresponding querying function will automatically take
270+-- an additional argument of the type specified by your 'ReqBody'.
271+-- That function will take care of encoding this argument as JSON and
272+-- of using it as the request body.
273+--
274+-- All you need is for your type to have a 'ToJSON' instance.
275+--
276+-- Example:
277+--
278+-- > type MyApi = "books" :> ReqBody Book :> Post Book
279+-- >
280+-- > myApi :: Proxy MyApi
281+-- > myApi = Proxy
282+-- >
283+-- > addBook :: Book -> BaseUrl -> EitherT String IO Book
284+-- > addBook = client myApi
285+-- > -- then you can just use "addBook" to query that endpoint
286+instance (ToJSON a, HasClient sublayout)
287+ => HasClient (ReqBody a :> sublayout) where
288+
289+ type Client (ReqBody a :> sublayout) =
290+ a -> Client sublayout
291+
292+ clientWithRoute Proxy req body =
293+ clientWithRoute (Proxy :: Proxy sublayout) $
294+ setRQBody (encode body) req
295+
296+-- | Make the querying function append @path@ to the request path.
297+instance (KnownSymbol path, HasClient sublayout) => HasClient (path :> sublayout) where
298+ type Client (path :> sublayout) = Client sublayout
299+
300+ clientWithRoute Proxy req =
301+ clientWithRoute (Proxy :: Proxy sublayout) $
302+ appendToPath p req
303+
304+ where p = symbolVal (Proxy :: Proxy path)
305+