git.iko.soy/typeable/servant
on master help sign in
Merge pull request #276 from haskell-servant/jkarni/emptyWithHeaders

Consolidate verbs

commit357cc839b65601975cb186a3f00a729f7f3bb2de authorJulian Arni <jkarni@gmail.com> dateFri 8 Jan 2016, 20:22 (11 years ago) parente007d8df9c6137
30 files changed+640−1018
servant-client/src/Servant/Client.hs+44−125 servant-client/src/Servant/Common/Req.hs+11−8 servant-client/test/Servant/ClientSpec.hs+7−7 servant-docs/src/Servant/Docs.hs+1−2 servant-docs/src/Servant/Docs/Internal.hs+31−133 servant-docs/test/Servant/DocsSpec.hs−1 servant-foreign/servant-foreign.cabal+6−4 servant-foreign/src/Servant/Foreign/Internal.hs+18−48 servant-foreign/test/Servant/ForeignSpec.hs+4−5 servant-js/src/Servant/JS/Angular.hs+2−1 servant-js/src/Servant/JS/Axios.hs+2−1 servant-js/src/Servant/JS/JQuery.hs+2−1 servant-js/src/Servant/JS/Vanilla.hs+2−1 servant-mock/src/Servant/Mock.hs+2−13 servant-server/src/Servant/Server/Internal.hs+41−206 servant-server/test/Servant/Server/ErrorSpec.hs+1−1 servant-server/test/Servant/Server/Internal/EnterSpec.hs+1−1 servant-server/test/Servant/ServerSpec.hs+226−252 servant-server/test/Servant/Utils/StaticFilesSpec.hs+1−6 servant/CHANGELOG.md+2 servant/servant.cabal+1−5 servant/src/Servant/API.hs+22−18 servant/src/Servant/API/ContentTypes.hs+38−23 servant/src/Servant/API/Delete.hs−24 servant/src/Servant/API/Get.hs−22 servant/src/Servant/API/Patch.hs−29 servant/src/Servant/API/Post.hs−27 servant/src/Servant/API/Put.hs−25 servant/src/Servant/API/Verbs.hs+169 servant/src/Servant/Utils/Links.hs+6−29
servant-client/src/Servant/Client.hs+44−125
@@ -4,6 +4,7 @@
44{-# LANGUAGE FlexibleInstances #-}
55{-# LANGUAGE InstanceSigs #-}
66{-# LANGUAGE OverloadedStrings #-}
7+{-# LANGUAGE PolyKinds #-}
78{-# LANGUAGE ScopedTypeVariables #-}
89{-# LANGUAGE TypeFamilies #-}
910{-# LANGUAGE TypeOperators #-}
@@ -23,7 +24,6 @@ module Servant.Client
2324#if !MIN_VERSION_base(4,8,0)
2425import Control.Applicative ((<$>))
2526#endif
26−import Control.Monad
2727import Control.Monad.Trans.Except
2828import Data.ByteString.Lazy (ByteString)
2929import Data.List
@@ -44,7 +44,7 @@ import Servant.Common.Req
4444-- | 'client' allows you to produce operations to query an API from a client.
4545--
4646-- > type MyApi = "books" :> Get '[JSON] [Book] -- GET /books
47−-- > :<|> "books" :> ReqBody '[JSON] Book :> Post Book -- POST /books
47+-- > :<|> "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book -- POST /books
4848-- >
4949-- > myApi :: Proxy MyApi
5050-- > myApi = Proxy
@@ -118,62 +118,48 @@ instance (KnownSymbol capture, ToHttpApiData a, HasClient sublayout)
118118
119119 where p = unpack (toUrlPiece val)
120120
121−-- | If you have a 'Delete' endpoint in your API, the client
122−-- side querying function that is created when calling 'client'
123−-- will just require an argument that specifies the scheme, host
124−-- and port to send the request to.
125121instance OVERLAPPABLE_
126− (MimeUnrender ct a, cts' ~ (ct ': cts)) => HasClient (Delete cts' a) where
127− type Client (Delete cts' a) = ExceptT ServantError IO a
122+ -- Note [Non-Empty Content Types]
123+ (MimeUnrender ct a, ReflectMethod method, cts' ~ (ct ': cts)
124+ ) => HasClient (Verb method status cts' a) where
125+ type Client (Verb method status cts' a) = ExceptT ServantError IO a
128126 clientWithRoute Proxy req baseurl manager =
129− snd <$> performRequestCT (Proxy :: Proxy ct) H.methodDelete req baseurl manager
127+ snd <$> performRequestCT (Proxy :: Proxy ct) method req baseurl manager
128+ where method = reflectMethod (Proxy :: Proxy method)
130129
131130instance OVERLAPPING_
132− HasClient (Delete cts ()) where
133− type Client (Delete cts ()) = ExceptT ServantError IO ()
131+ (ReflectMethod method) => HasClient (Verb method status cts NoContent) where
132+ type Client (Verb method status cts NoContent) = ExceptT ServantError IO NoContent
134133 clientWithRoute Proxy req baseurl manager =
135− void $ performRequestNoBody H.methodDelete req baseurl manager
134+ performRequestNoBody method req baseurl manager >> return NoContent
135+ where method = reflectMethod (Proxy :: Proxy method)
136136
137−-- | If you have a 'Delete xs (Headers ls x)' endpoint, the client expects the
138−-- corresponding headers.
139137instance OVERLAPPING_
140− ( MimeUnrender ct a, BuildHeadersTo ls, cts' ~ (ct ': cts)
141− ) => HasClient (Delete cts' (Headers ls a)) where
142− type Client (Delete cts' (Headers ls a)) = ExceptT ServantError IO (Headers ls a)
138+ -- Note [Non-Empty Content Types]
139+ ( MimeUnrender ct a, BuildHeadersTo ls, ReflectMethod method, cts' ~ (ct ': cts)
140+ ) => HasClient (Verb method status cts' (Headers ls a)) where
141+ type Client (Verb method status cts' (Headers ls a))
142+ = ExceptT ServantError IO (Headers ls a)
143143 clientWithRoute Proxy req baseurl manager = do
144− (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodDelete req baseurl manager
144+ let method = reflectMethod (Proxy :: Proxy method)
145+ (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) method req baseurl manager
145146 return $ Headers { getResponse = resp
146147 , getHeadersHList = buildHeadersTo hdrs
147148 }
148149
149−-- | If you have a 'Get' endpoint in your API, the client
150−-- side querying function that is created when calling 'client'
151−-- will just require an argument that specifies the scheme, host
152−-- and port to send the request to.
153−instance OVERLAPPABLE_
154− (MimeUnrender ct result) => HasClient (Get (ct ': cts) result) where
155− type Client (Get (ct ': cts) result) = ExceptT ServantError IO result
156− clientWithRoute Proxy req baseurl manager =
157− snd <$> performRequestCT (Proxy :: Proxy ct) H.methodGet req baseurl manager
158−
159−instance OVERLAPPING_
160− HasClient (Get (ct ': cts) ()) where
161− type Client (Get (ct ': cts) ()) = ExceptT ServantError IO ()
162− clientWithRoute Proxy req baseurl manager =
163− performRequestNoBody H.methodGet req baseurl manager
164−
165−-- | If you have a 'Get xs (Headers ls x)' endpoint, the client expects the
166−-- corresponding headers.
167150instance OVERLAPPING_
168− ( MimeUnrender ct a, BuildHeadersTo ls
169− ) => HasClient (Get (ct ': cts) (Headers ls a)) where
170− type Client (Get (ct ': cts) (Headers ls a)) = ExceptT ServantError IO (Headers ls a)
151+ ( BuildHeadersTo ls, ReflectMethod method
152+ ) => HasClient (Verb method status cts (Headers ls NoContent)) where
153+ type Client (Verb method status cts (Headers ls NoContent))
154+ = ExceptT ServantError IO (Headers ls NoContent)
171155 clientWithRoute Proxy req baseurl manager = do
172− (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodGet req baseurl manager
173− return $ Headers { getResponse = resp
156+ let method = reflectMethod (Proxy :: Proxy method)
157+ hdrs <- performRequestNoBody method req baseurl manager
158+ return $ Headers { getResponse = NoContent
174159 , getHeadersHList = buildHeadersTo hdrs
175160 }
176161
162+
177163-- | If you use a 'Header' in one of your endpoints in your API,
178164-- the corresponding querying function will automatically take
179165-- an additional argument of the type specified by your 'Header',
@@ -217,90 +203,6 @@ instance (KnownSymbol sym, ToHttpApiData a, HasClient sublayout)
217203
218204 where hname = symbolVal (Proxy :: Proxy sym)
219205
220−-- | If you have a 'Post' endpoint in your API, the client
221−-- side querying function that is created when calling 'client'
222−-- will just require an argument that specifies the scheme, host
223−-- and port to send the request to.
224−instance OVERLAPPABLE_
225− (MimeUnrender ct a) => HasClient (Post (ct ': cts) a) where
226− type Client (Post (ct ': cts) a) = ExceptT ServantError IO a
227− clientWithRoute Proxy req baseurl manager =
228− snd <$> performRequestCT (Proxy :: Proxy ct) H.methodPost req baseurl manager
229−
230−instance OVERLAPPING_
231− HasClient (Post (ct ': cts) ()) where
232− type Client (Post (ct ': cts) ()) = ExceptT ServantError IO ()
233− clientWithRoute Proxy req baseurl manager =
234− void $ performRequestNoBody H.methodPost req baseurl manager
235−
236−-- | If you have a 'Post xs (Headers ls x)' endpoint, the client expects the
237−-- corresponding headers.
238−instance OVERLAPPING_
239− ( MimeUnrender ct a, BuildHeadersTo ls
240− ) => HasClient (Post (ct ': cts) (Headers ls a)) where
241− type Client (Post (ct ': cts) (Headers ls a)) = ExceptT ServantError IO (Headers ls a)
242− clientWithRoute Proxy req baseurl manager = do
243− (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodPost req baseurl manager
244− return $ Headers { getResponse = resp
245− , getHeadersHList = buildHeadersTo hdrs
246− }
247−
248−-- | If you have a 'Put' endpoint in your API, the client
249−-- side querying function that is created when calling 'client'
250−-- will just require an argument that specifies the scheme, host
251−-- and port to send the request to.
252−instance OVERLAPPABLE_
253− (MimeUnrender ct a) => HasClient (Put (ct ': cts) a) where
254− type Client (Put (ct ': cts) a) = ExceptT ServantError IO a
255− clientWithRoute Proxy req baseurl manager =
256− snd <$> performRequestCT (Proxy :: Proxy ct) H.methodPut req baseurl manager
257−
258−instance OVERLAPPING_
259− HasClient (Put (ct ': cts) ()) where
260− type Client (Put (ct ': cts) ()) = ExceptT ServantError IO ()
261− clientWithRoute Proxy req baseurl manager =
262− void $ performRequestNoBody H.methodPut req baseurl manager
263−
264−-- | If you have a 'Put xs (Headers ls x)' endpoint, the client expects the
265−-- corresponding headers.
266−instance OVERLAPPING_
267− ( MimeUnrender ct a, BuildHeadersTo ls
268− ) => HasClient (Put (ct ': cts) (Headers ls a)) where
269− type Client (Put (ct ': cts) (Headers ls a)) = ExceptT ServantError IO (Headers ls a)
270− clientWithRoute Proxy req baseurl manager= do
271− (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodPut req baseurl manager
272− return $ Headers { getResponse = resp
273− , getHeadersHList = buildHeadersTo hdrs
274− }
275−
276−-- | If you have a 'Patch' endpoint in your API, the client
277−-- side querying function that is created when calling 'client'
278−-- will just require an argument that specifies the scheme, host
279−-- and port to send the request to.
280−instance OVERLAPPABLE_
281− (MimeUnrender ct a) => HasClient (Patch (ct ': cts) a) where
282− type Client (Patch (ct ': cts) a) = ExceptT ServantError IO a
283− clientWithRoute Proxy req baseurl manager =
284− snd <$> performRequestCT (Proxy :: Proxy ct) H.methodPatch req baseurl manager
285−
286−instance OVERLAPPING_
287− HasClient (Patch (ct ': cts) ()) where
288− type Client (Patch (ct ': cts) ()) = ExceptT ServantError IO ()
289− clientWithRoute Proxy req baseurl manager =
290− void $ performRequestNoBody H.methodPatch req baseurl manager
291−
292−-- | If you have a 'Patch xs (Headers ls x)' endpoint, the client expects the
293−-- corresponding headers.
294−instance OVERLAPPING_
295− ( MimeUnrender ct a, BuildHeadersTo ls
296− ) => HasClient (Patch (ct ': cts) (Headers ls a)) where
297− type Client (Patch (ct ': cts) (Headers ls a)) = ExceptT ServantError IO (Headers ls a)
298− clientWithRoute Proxy req baseurl manager = do
299− (hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodPatch req baseurl manager
300− return $ Headers { getResponse = resp
301− , getHeadersHList = buildHeadersTo hdrs
302− }
303−
304206-- | If you use a 'QueryParam' in one of your endpoints in your API,
305207-- the corresponding querying function will automatically take
306208-- an additional argument of the type specified by your 'QueryParam',
@@ -503,3 +405,20 @@ instance HasClient api => HasClient (IsSecure :> api) where
503405
504406 clientWithRoute Proxy req baseurl manager =
505407 clientWithRoute (Proxy :: Proxy api) req baseurl manager
408+
409+
410+{- Note [Non-Empty Content Types]
411+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
412+Rather than have
413+
414+ instance (..., cts' ~ (ct ': cts)) => ... cts' ...
415+
416+It may seem to make more sense to have:
417+
418+ instance (...) => ... (ct ': cts) ...
419+
420+But this means that if another instance exists that does *not* require
421+non-empty lists, but is otherwise more specific, no instance will be overall
422+more specific. This in turn generally means adding yet another instance (one
423+for empty and one for non-empty lists).
424+-}
servant-client/src/Servant/Common/Req.hs+11−8
@@ -142,7 +142,7 @@ performRequest reqMethod req reqHost manager = do
142142 Right response -> do
143143 let status = Client.responseStatus response
144144 body = Client.responseBody response
145− hrds = Client.responseHeaders response
145+ hdrs = Client.responseHeaders response
146146 status_code = statusCode status
147147 ct <- case lookup "Content-Type" $ Client.responseHeaders response of
148148 Nothing -> pure $ "application"//"octet-stream"
@@ -151,23 +151,26 @@ performRequest reqMethod req reqHost manager = do
151151 Just t' -> pure t'
152152 unless (status_code >= 200 && status_code < 300) $
153153 throwE $ FailureResponse status ct body
154− return (status_code, body, ct, hrds, response)
154+ return (status_code, body, ct, hdrs, response)
155155
156156
157157performRequestCT :: MimeUnrender ct result =>
158− Proxy ct -> Method -> Req -> BaseUrl -> Manager -> ExceptT ServantError IO ([HTTP.Header], result)
158+ Proxy ct -> Method -> Req -> BaseUrl -> Manager
159+ -> ExceptT ServantError IO ([HTTP.Header], result)
159160performRequestCT ct reqMethod req reqHost manager = do
160161 let acceptCT = contentType ct
161− (_status, respBody, respCT, hrds, _response) <-
162+ (_status, respBody, respCT, hdrs, _response) <-
162163 performRequest reqMethod (req { reqAccept = [acceptCT] }) reqHost manager
163164 unless (matches respCT (acceptCT)) $ throwE $ UnsupportedContentType respCT respBody
164165 case mimeUnrender ct respBody of
165166 Left err -> throwE $ DecodeFailure err respCT respBody
166− Right val -> return (hrds, val)
167+ Right val -> return (hdrs, val)
167168
168−performRequestNoBody :: Method -> Req -> BaseUrl -> Manager -> ExceptT ServantError IO ()
169−performRequestNoBody reqMethod req reqHost manager =
170− void $ performRequest reqMethod req reqHost manager
169+performRequestNoBody :: Method -> Req -> BaseUrl -> Manager
170+ -> ExceptT ServantError IO [HTTP.Header]
171+performRequestNoBody reqMethod req reqHost manager = do
172+ (_status, _body, _ct, hdrs, _response) <- performRequest reqMethod req reqHost manager
173+ return hdrs
171174
172175catchConnectionError :: IO a -> IO (Either ServantError a)
173176catchConnectionError action =
servant-client/test/Servant/ClientSpec.hs+7−7
@@ -90,7 +90,7 @@ type TestHeaders = '[Header "X-Example1" Int, Header "X-Example2" String]
9090
9191type Api =
9292 "get" :> Get '[JSON] Person
93− :<|> "deleteEmpty" :> Delete '[] ()
93+ :<|> "deleteEmpty" :> DeleteNoContent '[JSON] NoContent
9494 :<|> "capture" :> Capture "name" String :> Get '[JSON,FormUrlEncoded] Person
9595 :<|> "body" :> ReqBody '[FormUrlEncoded,JSON] Person :> Post '[JSON] Person
9696 :<|> "param" :> QueryParam "name" String :> Get '[FormUrlEncoded,JSON] Person
@@ -105,14 +105,14 @@ type Api =
105105 ReqBody '[JSON] [(String, [Rational])] :>
106106 Get '[JSON] (String, Maybe Int, Bool, [(String, [Rational])])
107107 :<|> "headers" :> Get '[JSON] (Headers TestHeaders Bool)
108− :<|> "deleteContentType" :> Delete '[JSON] ()
108+ :<|> "deleteContentType" :> DeleteNoContent '[JSON] NoContent
109109api :: Proxy Api
110110api = Proxy
111111
112112server :: Application
113113server = serve api (
114114 return alice
115− :<|> return ()
115+ :<|> return NoContent
116116 :<|> (\ name -> return $ Person name 0)
117117 :<|> return
118118 :<|> (\ name -> case name of
@@ -125,7 +125,7 @@ server = serve api (
125125 :<|> (\ _request respond -> respond $ responseLBS badRequest400 [] "rawFailure")
126126 :<|> (\ a b c d -> return (a, b, c, d))
127127 :<|> (return $ addHeader 1729 $ addHeader "eg2" True)
128− :<|> return ()
128+ :<|> return NoContent
129129 )
130130
131131
@@ -157,11 +157,11 @@ sucessSpec = beforeAll (startWaiApp server) $ afterAll endWaiApp $ do
157157 describe "Servant.API.Delete" $ do
158158 it "allows empty content type" $ \(_, baseUrl) -> do
159159 let getDeleteEmpty = getNth (Proxy :: Proxy 1) $ client api baseUrl manager
160− (left show <$> runExceptT getDeleteEmpty) `shouldReturn` Right ()
160+ (left show <$> runExceptT getDeleteEmpty) `shouldReturn` Right NoContent
161161
162162 it "allows content type" $ \(_, baseUrl) -> do
163163 let getDeleteContentType = getLast $ client api baseUrl manager
164− (left show <$> runExceptT getDeleteContentType) `shouldReturn` Right ()
164+ (left show <$> runExceptT getDeleteContentType) `shouldReturn` Right NoContent
165165
166166 it "Servant.API.Capture" $ \(_, baseUrl) -> do
167167 let getCapture = getNth (Proxy :: Proxy 2) $ client api baseUrl manager
@@ -283,7 +283,7 @@ failSpec = beforeAll (startWaiApp failServer) $ afterAll endWaiApp $ do
283283 _ -> fail $ "expected InvalidContentTypeHeader, but got " <> show res
284284
285285data WrappedApi where
286− WrappedApi :: (HasServer api, Server api ~ ExceptT ServantErr IO a,
286+ WrappedApi :: (HasServer (api :: *), Server api ~ ExceptT ServantErr IO a,
287287 HasClient api, Client api ~ ExceptT ServantError IO ()) =>
288288 Proxy api -> WrappedApi
289289
servant-docs/src/Servant/Docs.hs+1−2
@@ -41,8 +41,7 @@ module Servant.Docs
4141 , ToCapture(..)
4242
4343 , -- * ADTs to represent an 'API'
44− Method(..)
45− , Endpoint, path, method, defEndpoint
44+ Endpoint, path, method, defEndpoint
4645 , API, apiIntros, apiEndpoints, emptyAPI
4746 , DocCapture(..), capSymbol, capDesc
4847 , DocQueryParam(..), ParamKind(..), paramName, paramValues, paramDesc, paramKind
servant-docs/src/Servant/Docs/Internal.hs+31−133
@@ -36,7 +36,7 @@ import Data.Monoid
3636import Data.Ord (comparing)
3737import Data.Proxy (Proxy(Proxy))
3838import Data.String.Conversions (cs)
39−import Data.Text (Text, pack, unpack)
39+import Data.Text (Text, unpack)
4040import GHC.Exts (Constraint)
4141import GHC.Generics
4242import GHC.TypeLits
@@ -49,21 +49,6 @@ import qualified Data.Text as T
4949import qualified Network.HTTP.Media as M
5050import qualified Network.HTTP.Types as HTTP
5151
52−-- | Supported HTTP request methods
53−data Method = DocDELETE -- ^ the DELETE method
54− | DocGET -- ^ the GET method
55− | DocPOST -- ^ the POST method
56− | DocPUT -- ^ the PUT method
57− deriving (Eq, Ord, Generic)
58−
59−instance Show Method where
60− show DocGET = "GET"
61− show DocPOST = "POST"
62− show DocDELETE = "DELETE"
63− show DocPUT = "PUT"
64−
65−instance Hashable Method
66−
6752-- | An 'Endpoint' type that holds the 'path' and the 'method'.
6853--
6954-- Gets used as the key in the 'API' hashmap. Modify 'defEndpoint'
@@ -75,12 +60,12 @@ instance Hashable Method
7560-- GET /
7661-- λ> 'defEndpoint' & 'path' '<>~' ["foo"]
7762-- GET /foo
78−-- λ> 'defEndpoint' & 'path' '<>~' ["foo"] & 'method' '.~' 'DocPOST'
63+-- λ> 'defEndpoint' & 'path' '<>~' ["foo"] & 'method' '.~' 'HTTP.methodPost'
7964-- POST /foo
8065-- @
8166data Endpoint = Endpoint
82− { _path :: [String] -- type collected
83− , _method :: Method -- type collected
67+ { _path :: [String] -- type collected
68+ , _method :: HTTP.Method -- type collected
8469 } deriving (Eq, Ord, Generic)
8570
8671instance Show Endpoint where
@@ -94,7 +79,7 @@ showPath :: [String] -> String
9479showPath [] = "/"
9580showPath ps = concatMap ('/' :) ps
9681
97−-- | An 'Endpoint' whose path is `"/"` and whose method is 'DocGET'
82+-- | An 'Endpoint' whose path is `"/"` and whose method is @GET@
9883--
9984-- Here's how you can modify it:
10085--
@@ -103,11 +88,11 @@ showPath ps = concatMap ('/' :) ps
10388-- GET /
10489-- λ> 'defEndpoint' & 'path' '<>~' ["foo"]
10590-- GET /foo
106−-- λ> 'defEndpoint' & 'path' '<>~' ["foo"] & 'method' '.~' 'DocPOST'
91+-- λ> 'defEndpoint' & 'path' '<>~' ["foo"] & 'method' '.~' 'HTTP.methodPost'
10792-- POST /foo
10893-- @
10994defEndpoint :: Endpoint
110−defEndpoint = Endpoint [] DocGET
95+defEndpoint = Endpoint [] HTTP.methodGet
11196
11297instance Hashable Endpoint
11398
@@ -476,8 +461,8 @@ instance (ToByteString l, AllHeaderSamples ls, ToSample l, KnownSymbol h)
476461
477462-- | Synthesise a sample value of a type, encoded in the specified media types.
478463sampleByteString
479− :: forall ctypes a. (ToSample a, IsNonEmpty ctypes, AllMimeRender ctypes a)
480− => Proxy ctypes
464+ :: forall ct cts a. (ToSample a, AllMimeRender (ct ': cts) a)
465+ => Proxy (ct ': cts)
481466 -> Proxy a
482467 -> [(M.MediaType, ByteString)]
483468sampleByteString ctypes@Proxy Proxy =
@@ -486,8 +471,8 @@ sampleByteString ctypes@Proxy Proxy =
486471-- | Synthesise a list of sample values of a particular type, encoded in the
487472-- specified media types.
488473sampleByteStrings
489− :: forall ctypes a. (ToSample a, IsNonEmpty ctypes, AllMimeRender ctypes a)
490− => Proxy ctypes
474+ :: forall ct cts a. (ToSample a, AllMimeRender (ct ': cts) a)
475+ => Proxy (ct ': cts)
491476 -> Proxy a
492477 -> [(Text, M.MediaType, ByteString)]
493478sampleByteStrings ctypes@Proxy Proxy =
@@ -689,124 +674,37 @@ instance (KnownSymbol sym, ToCapture (Capture sym a), HasDocs sublayout)
689674
690675
691676instance OVERLAPPABLE_
692− (ToSample a, IsNonEmpty cts, AllMimeRender cts a)
693− => HasDocs (Delete cts a) where
694− docsFor Proxy (endpoint, action) DocOptions{..} =
695− single endpoint' action'
696−
697− where endpoint' = endpoint & method .~ DocDELETE
698− action' = action & response.respBody .~ take _maxSamples (sampleByteStrings t p)
699− & response.respTypes .~ allMime t
700− t = Proxy :: Proxy cts
701− p = Proxy :: Proxy a
702−
703−instance OVERLAPPING_
704− (ToSample a, IsNonEmpty cts, AllMimeRender cts a
705− , AllHeaderSamples ls , GetHeaders (HList ls) )
706− => HasDocs (Delete cts (Headers ls a)) where
707− docsFor Proxy (endpoint, action) DocOptions{..} =
708− single endpoint' action'
709−
710− where hdrs = allHeaderToSample (Proxy :: Proxy ls)
711− endpoint' = endpoint & method .~ DocDELETE
712− action' = action & response.respBody .~ take _maxSamples (sampleByteStrings t p)
713− & response.respTypes .~ allMime t
714− & response.respHeaders .~ hdrs
715− t = Proxy :: Proxy cts
716− p = Proxy :: Proxy a
717−
718−instance OVERLAPPABLE_
719− (ToSample a, IsNonEmpty cts, AllMimeRender cts a)
720− => HasDocs (Get cts a) where
721− docsFor Proxy (endpoint, action) DocOptions{..} =
722− single endpoint' action'
723−
724− where endpoint' = endpoint & method .~ DocGET
725− action' = action & response.respBody .~ take _maxSamples (sampleByteStrings t p)
726− & response.respTypes .~ allMime t
727− t = Proxy :: Proxy cts
728− p = Proxy :: Proxy a
729−
730−instance OVERLAPPING_
731− (ToSample a, IsNonEmpty cts, AllMimeRender cts a
732− , AllHeaderSamples ls , GetHeaders (HList ls) )
733− => HasDocs (Get cts (Headers ls a)) where
734− docsFor Proxy (endpoint, action) DocOptions{..} =
735− single endpoint' action'
736−
737− where hdrs = allHeaderToSample (Proxy :: Proxy ls)
738− endpoint' = endpoint & method .~ DocGET
739− action' = action & response.respBody .~ take _maxSamples (sampleByteStrings t p)
740− & response.respTypes .~ allMime t
741− & response.respHeaders .~ hdrs
742− t = Proxy :: Proxy cts
743− p = Proxy :: Proxy a
744−
745−instance (KnownSymbol sym, HasDocs sublayout)
746− => HasDocs (Header sym a :> sublayout) where
747− docsFor Proxy (endpoint, action) =
748− docsFor sublayoutP (endpoint, action')
749−
750− where sublayoutP = Proxy :: Proxy sublayout
751− action' = over headers (|> headername) action
752− headername = pack $ symbolVal (Proxy :: Proxy sym)
753−
754−instance OVERLAPPABLE_
755− (ToSample a, IsNonEmpty cts, AllMimeRender cts a)
756− => HasDocs (Post cts a) where
757− docsFor Proxy (endpoint, action) DocOptions{..} =
758− single endpoint' action'
759−
760− where endpoint' = endpoint & method .~ DocPOST
761− action' = action & response.respBody .~ take _maxSamples (sampleByteStrings t p)
762− & response.respTypes .~ allMime t
763− & response.respStatus .~ 201
764− t = Proxy :: Proxy cts
765− p = Proxy :: Proxy a
766−
767−instance OVERLAPPING_
768− (ToSample a, IsNonEmpty cts, AllMimeRender cts a
769− , AllHeaderSamples ls , GetHeaders (HList ls) )
770− => HasDocs (Post cts (Headers ls a)) where
771− docsFor Proxy (endpoint, action) DocOptions{..} =
772− single endpoint' action'
773−
774− where hdrs = allHeaderToSample (Proxy :: Proxy ls)
775− endpoint' = endpoint & method .~ DocPOST
776− action' = action & response.respBody .~ take _maxSamples (sampleByteStrings t p)
777− & response.respTypes .~ allMime t
778− & response.respStatus .~ 201
779− & response.respHeaders .~ hdrs
780− t = Proxy :: Proxy cts
781− p = Proxy :: Proxy a
782−
783−instance OVERLAPPABLE_
784− (ToSample a, IsNonEmpty cts, AllMimeRender cts a)
785− => HasDocs (Put cts a) where
677+ (ToSample a, AllMimeRender (ct ': cts) a, KnownNat status
678+ , ReflectMethod method)
679+ => HasDocs (Verb method status (ct ': cts) a) where
786680 docsFor Proxy (endpoint, action) DocOptions{..} =
787681 single endpoint' action'
788682
789− where endpoint' = endpoint & method .~ DocPUT
683+ where endpoint' = endpoint & method .~ method'
790684 action' = action & response.respBody .~ take _maxSamples (sampleByteStrings t p)
791685 & response.respTypes .~ allMime t
792− & response.respStatus .~ 200
793− t = Proxy :: Proxy cts
686+ & response.respStatus .~ status
687+ t = Proxy :: Proxy (ct ': cts)
688+ method' = reflectMethod (Proxy :: Proxy method)
689+ status = fromInteger $ natVal (Proxy :: Proxy status)
794690 p = Proxy :: Proxy a
795691
796692instance OVERLAPPING_
797− ( ToSample a, IsNonEmpty cts, AllMimeRender cts a,
798− AllHeaderSamples ls , GetHeaders (HList ls) )
799− => HasDocs (Put cts (Headers ls a)) where
693+ (ToSample a, AllMimeRender (ct ': cts) a, KnownNat status
694+ , ReflectMethod method, AllHeaderSamples ls, GetHeaders (HList ls))
695+ => HasDocs (Verb method status (ct ': cts) (Headers ls a)) where
800696 docsFor Proxy (endpoint, action) DocOptions{..} =
801697 single endpoint' action'
802698
803− where hdrs = allHeaderToSample (Proxy :: Proxy ls)
804− endpoint' = endpoint & method .~ DocPUT
699+ where endpoint' = endpoint & method .~ method'
805700 action' = action & response.respBody .~ take _maxSamples (sampleByteStrings t p)
806701 & response.respTypes .~ allMime t
807− & response.respStatus .~ 200
702+ & response.respStatus .~ status
808703 & response.respHeaders .~ hdrs
809− t = Proxy :: Proxy cts
704+ t = Proxy :: Proxy (ct ': cts)
705+ hdrs = allHeaderToSample (Proxy :: Proxy ls)
706+ method' = reflectMethod (Proxy :: Proxy method)
707+ status = fromInteger $ natVal (Proxy :: Proxy status)
810708 p = Proxy :: Proxy a
811709
812710instance (KnownSymbol sym, ToParam (QueryParam sym a), HasDocs sublayout)
@@ -849,8 +747,8 @@ instance HasDocs Raw where
849747-- example data. However, there's no reason to believe that the instances of
850748-- 'AllMimeUnrender' and 'AllMimeRender' actually agree (or to suppose that
851749-- both are even defined) for any particular type.
852−instance (ToSample a, IsNonEmpty cts, AllMimeRender cts a, HasDocs sublayout)
853− => HasDocs (ReqBody cts a :> sublayout) where
750+instance (ToSample a, AllMimeRender (ct ': cts) a, HasDocs sublayout)
751+ => HasDocs (ReqBody (ct ': cts) a :> sublayout) where
854752
855753 docsFor Proxy (endpoint, action) =
856754 docsFor sublayoutP (endpoint, action')
@@ -858,7 +756,7 @@ instance (ToSample a, IsNonEmpty cts, AllMimeRender cts a, HasDocs sublayout)
858756 where sublayoutP = Proxy :: Proxy sublayout
859757 action' = action & rqbody .~ sampleByteString t p
860758 & rqtypes .~ allMime t
861− t = Proxy :: Proxy cts
759+ t = Proxy :: Proxy (ct ': cts)
862760 p = Proxy :: Proxy a
863761
864762instance (KnownSymbol path, HasDocs sublayout) => HasDocs (path :> sublayout) where
servant-docs/test/Servant/DocsSpec.hs−1
@@ -71,7 +71,6 @@ spec = describe "Servant.Docs" $ do
7171
7272 it "mentions status codes" $ do
7373 md `shouldContain` "Status code 200"
74− md `shouldContain` "Status code 201"
7574
7675 it "mentions methods" $ do
7776 md `shouldContain` "POST"
servant-foreign/servant-foreign.cabal+6−4
@@ -27,10 +27,11 @@ source-repository head
2727
2828library
2929 exposed-modules: Servant.Foreign, Servant.Foreign.Internal
30− build-depends: base == 4.*
31− , lens == 4.*
32− , servant == 0.5.*
33− , text >= 1.2 && < 1.3
30+ build-depends: base == 4.*
31+ , lens == 4.*
32+ , servant == 0.5.*
33+ , text >= 1.2 && < 1.3
34+ , http-types
3435 hs-source-dirs: src
3536 default-language: Haskell2010
3637 ghc-options: -Wall
@@ -41,6 +42,7 @@ test-suite spec
4142 type: exitcode-stdio-1.0
4243 hs-source-dirs: test
4344 ghc-options: -Wall
45+ include-dirs: include
4446 main-is: Spec.hs
4547 other-modules:
4648 Servant.ForeignSpec
servant-foreign/src/Servant/Foreign/Internal.hs+18−48
@@ -13,18 +13,21 @@
1313{-# LANGUAGE TypeOperators #-}
1414{-# LANGUAGE UndecidableInstances #-}
1515{-# LANGUAGE OverloadedStrings #-}
16+{-# LANGUAGE PolyKinds #-}
1617
1718-- | Generalizes all the data needed to make code generation work with
1819-- arbitrary programming languages.
1920module Servant.Foreign.Internal where
2021
21−import Control.Lens (makeLenses, (%~), (&), (.~), (<>~))
22−import qualified Data.Char as C
22+import Control.Lens (makeLenses, (%~), (&), (.~), (<>~))
23+import qualified Data.Char as C
2324import Data.Proxy
2425import Data.Text
25−import GHC.Exts (Constraint)
26+import Data.Text.Encoding (decodeUtf8)
27+import GHC.Exts (Constraint)
2628import GHC.TypeLits
27−import Prelude hiding (concat)
29+import qualified Network.HTTP.Types as HTTP
30+import Prelude hiding (concat)
2831import Servant.API
2932
3033-- | Function name builder that simply concat each part together
@@ -86,11 +89,10 @@ defUrl :: Url
8689defUrl = Url [] []
8790
8891type FunctionName = [Text]
89−type Method = Text
9092
9193data Req = Req
9294 { _reqUrl :: Url
93− , _reqMethod :: Method
95+ , _reqMethod :: HTTP.Method
9496 , _reqHeaders :: [HeaderArg]
9597 , _reqBody :: Maybe ForeignType
9698 , _reqReturnType :: ForeignType
@@ -185,27 +187,18 @@ instance (KnownSymbol sym, HasForeignType lang a, HasForeign lang sublayout)
185187 str = pack . symbolVal $ (Proxy :: Proxy sym)
186188 arg = (str, typeFor lang (Proxy :: Proxy a))
187189
188−instance (Elem JSON list, HasForeignType lang a)
189− => HasForeign lang (Delete list a) where
190− type Foreign (Delete list a) = Req
190+instance (Elem JSON list, HasForeignType lang a, ReflectMethod method)
191+ => HasForeign lang (Verb method status list a) where
192+ type Foreign (Verb method status list a) = Req
191193
192194 foreignFor lang Proxy req =
193− req & funcName %~ ("delete" :)
194− & reqMethod .~ "DELETE"
195− & reqReturnType .~ retType
196− where
197− retType = typeFor lang (Proxy :: Proxy a)
198−
199−instance (Elem JSON list, HasForeignType lang a)
200− => HasForeign lang (Get list a) where
201− type Foreign (Get list a) = Req
202−
203− foreignFor lang Proxy req =
204− req & funcName %~ ("get" :)
205− & reqMethod .~ "GET"
195+ req & funcName %~ (methodLC :)
196+ & reqMethod .~ method
206197 & reqReturnType .~ retType
207198 where
208− retType = typeFor lang (Proxy :: Proxy a)
199+ retType = typeFor lang (Proxy :: Proxy a)
200+ method = reflectMethod (Proxy :: Proxy method)
201+ methodLC = toLower $ decodeUtf8 method
209202
210203instance (KnownSymbol sym, HasForeignType lang a, HasForeign lang sublayout)
211204 => HasForeign lang (Header sym a :> sublayout) where
@@ -220,28 +213,6 @@ instance (KnownSymbol sym, HasForeignType lang a, HasForeign lang sublayout)
220213 arg = (hname, typeFor lang (Proxy :: Proxy a))
221214 subP = Proxy :: Proxy sublayout
222215
223−instance (Elem JSON list, HasForeignType lang a)
224− => HasForeign lang (Post list a) where
225− type Foreign (Post list a) = Req
226−
227− foreignFor lang Proxy req =
228− req & funcName %~ ("post" :)
229− & reqMethod .~ "POST"
230− & reqReturnType .~ retType
231− where
232− retType = typeFor lang (Proxy :: Proxy a)
233−
234−instance (Elem JSON list, HasForeignType lang a)
235− => HasForeign lang (Put list a) where
236− type Foreign (Put list a) = Req
237−
238− foreignFor lang Proxy req =
239− req & funcName %~ ("put" :)
240− & reqMethod .~ "PUT"
241− & reqReturnType .~ retType
242− where
243− retType = typeFor lang (Proxy :: Proxy a)
244−
245216instance (KnownSymbol sym, HasForeignType lang a, HasForeign lang sublayout)
246217 => HasForeign lang (QueryParam sym a :> sublayout) where
247218 type Foreign (QueryParam sym a :> sublayout) = Foreign sublayout
@@ -279,10 +250,10 @@ instance (KnownSymbol sym, HasForeignType lang a, a ~ Bool, HasForeign lang subl
279250 arg = (str, typeFor lang (Proxy :: Proxy a))
280251
281252instance HasForeign lang Raw where
282− type Foreign Raw = Method -> Req
253+ type Foreign Raw = HTTP.Method -> Req
283254
284255 foreignFor _ Proxy req method =
285− req & funcName %~ ((toLower method) :)
256+ req & funcName %~ ((toLower $ decodeUtf8 method) :)
286257 & reqMethod .~ method
287258
288259instance (Elem JSON list, HasForeignType lang a, HasForeign lang sublayout)
@@ -346,4 +317,3 @@ instance (GenerateList start, GenerateList rest) => GenerateList (start :<|> res
346317-- describing one endpoint from your API type.
347318listFromAPI :: (HasForeign lang api, GenerateList (Foreign api)) => Proxy lang -> Proxy api -> [Req]
348319listFromAPI lang p = generateList (foreignFor lang p defReq)
349−
servant-foreign/test/Servant/ForeignSpec.hs+4−5
@@ -7,9 +7,8 @@
77{-# LANGUAGE TypeSynonymInstances #-}
88{-# LANGUAGE ScopedTypeVariables #-}
99{-# LANGUAGE CPP #-}
10−#if __GLASGOW_HASKELL__ < 710
11−{-# LANGUAGE OverlappingInstances #-}
12−#endif
10+
11+#include "overlapping-compat.h"
1312
1413module Servant.ForeignSpec where
1514
@@ -41,9 +40,9 @@ instance HasForeignType LangX Int where
4140 typeFor _ _ = "intX"
4241instance HasForeignType LangX Bool where
4342 typeFor _ _ = "boolX"
44−instance {-# Overlapping #-} HasForeignType LangX String where
43+instance OVERLAPPING_ HasForeignType LangX String where
4544 typeFor _ _ = "stringX"
46−instance {-# Overlappable #-} HasForeignType LangX a => HasForeignType LangX [a] where
45+instance OVERLAPPABLE_ HasForeignType LangX a => HasForeignType LangX [a] where
4746 typeFor lang _ = "listX of " <> typeFor lang (Proxy :: Proxy a)
4847
4948type TestApi
servant-js/src/Servant/JS/Angular.hs+2−1
@@ -6,6 +6,7 @@ import Data.Maybe (isJust)
66import Data.Monoid
77import qualified Data.Text as T
88import Data.Text (Text)
9+import Data.Text.Encoding (decodeUtf8)
910import Servant.Foreign
1011import Servant.JS.Internal
1112
@@ -68,7 +69,7 @@ generateAngularJSWith ngOptions opts req = "\n" <>
6869 <> " { url: " <> url <> "\n"
6970 <> dataBody
7071 <> reqheaders
71− <> " , method: '" <> method <> "'\n"
72+ <> " , method: '" <> decodeUtf8 method <> "'\n"
7273 <> " });\n"
7374 <> "}\n"
7475
servant-js/src/Servant/JS/Axios.hs+2−1
@@ -5,6 +5,7 @@ import Control.Lens
55import Data.Maybe (isJust)
66import Data.Monoid
77import Data.Text (Text)
8+import Data.Text.Encoding (decodeUtf8)
89import qualified Data.Text as T
910import Servant.Foreign
1011import Servant.JS.Internal
@@ -117,7 +118,7 @@ generateAxiosJSWith aopts opts req = "\n" <>
117118
118119 fname = namespace <> (functionNameBuilder opts $ req ^. funcName)
119120
120− method = T.toLower $ req ^. reqMethod
121+ method = T.toLower . decodeUtf8 $ req ^. reqMethod
121122 url = if url' == "'" then "'/'" else url'
122123 url' = "'"
123124 <> urlPrefix opts
servant-js/src/Servant/JS/JQuery.hs+2−1
@@ -6,6 +6,7 @@ import Data.Maybe (isJust)
66import Data.Monoid
77import qualified Data.Text as T
88import Data.Text (Text)
9+import Data.Text.Encoding (decodeUtf8)
910import Servant.Foreign
1011import Servant.JS.Internal
1112
@@ -35,7 +36,7 @@ generateJQueryJSWith opts req = "\n" <>
3536 <> dataBody
3637 <> reqheaders
3738 <> " , error: " <> onError <> "\n"
38− <> " , type: '" <> method <> "'\n"
39+ <> " , type: '" <> decodeUtf8 method <> "'\n"
3940 <> " });\n"
4041 <> "}\n"
4142
servant-js/src/Servant/JS/Vanilla.hs+2−1
@@ -4,6 +4,7 @@ module Servant.JS.Vanilla where
44import Control.Lens
55import Data.Maybe (isJust)
66import Data.Text (Text)
7+import Data.Text.Encoding (decodeUtf8)
78import qualified Data.Text as T
89import Data.Monoid
910import Servant.Foreign
@@ -31,7 +32,7 @@ generateVanillaJSWith opts req = "\n" <>
3132 fname <> " = function(" <> argsStr <> ")\n"
3233 <> "{\n"
3334 <> " var xhr = new XMLHttpRequest();\n"
34− <> " xhr.open('" <> method <> "', " <> url <> ", true);\n"
35+ <> " xhr.open('" <> decodeUtf8 method <> "', " <> url <> ", true);\n"
3536 <> reqheaders
3637 <> " xhr.setRequestHeader(\"Accept\",\"application/json\");\n"
3738 <> (if isJust (req ^. reqBody) then " xhr.setRequestHeader(\"Content-Type\",\"application/json\");\n" else "")
servant-mock/src/Servant/Mock.hs+2−13
@@ -139,19 +139,8 @@ instance (KnownSymbol s, HasMock rest) => HasMock (QueryFlag s :> rest) where
139139instance (KnownSymbol h, FromHttpApiData a, HasMock rest) => HasMock (Header h a :> rest) where
140140 mock _ = \_ -> mock (Proxy :: Proxy rest)
141141
142−instance (Arbitrary a, AllCTRender ctypes a) => HasMock (Delete ctypes a) where
143− mock _ = mockArbitrary
144−
145−instance (Arbitrary a, AllCTRender ctypes a) => HasMock (Get ctypes a) where
146− mock _ = mockArbitrary
147−
148−instance (Arbitrary a, AllCTRender ctypes a) => HasMock (Patch ctypes a) where
149− mock _ = mockArbitrary
150−
151−instance (Arbitrary a, AllCTRender ctypes a) => HasMock (Post ctypes a) where
152− mock _ = mockArbitrary
153−
154−instance (Arbitrary a, AllCTRender ctypes a) => HasMock (Put ctypes a) where
142+instance (Arbitrary a, KnownNat status, ReflectMethod method, AllCTRender ctypes a)
143+ => HasMock (Verb method status ctypes a) where
155144 mock _ = mockArbitrary
156145
157146instance HasMock Raw where
servant-server/src/Servant/Server/Internal.hs+41−206
@@ -21,26 +21,33 @@ module Servant.Server.Internal
2121#if !MIN_VERSION_base(4,8,0)
2222import Control.Applicative ((<$>))
2323#endif
24−import Control.Monad.Trans.Except (ExceptT)
25−import qualified Data.ByteString as B
26−import qualified Data.ByteString.Lazy as BL
27−import qualified Data.Map as M
28−import Data.Maybe (fromMaybe, mapMaybe)
29−import Data.String (fromString)
30−import Data.String.Conversions (ConvertibleStrings, cs, (<>))
31−import Data.Text (Text)
24+import Control.Monad.Trans.Except (ExceptT)
25+import qualified Data.ByteString as B
26+import qualified Data.ByteString.Lazy as BL
27+import qualified Data.Map as M
28+import Data.Maybe (fromMaybe, mapMaybe)
29+import Data.String (fromString)
30+import Data.String.Conversions (cs, (<>))
31+import Data.Text (Text)
3232import Data.Typeable
33−import GHC.TypeLits (KnownSymbol, symbolVal)
34−import Network.HTTP.Types hiding (Header, ResponseHeaders)
35−import Network.Socket (SockAddr)
36−import Network.Wai (Application, lazyRequestBody,
37− rawQueryString, requestHeaders,
38− requestMethod, responseLBS, remoteHost,
39− isSecure, vault, httpVersion, Response,
40− Request, pathInfo)
33+import GHC.TypeLits (KnownNat, KnownSymbol, natVal,
34+ symbolVal)
35+import Network.HTTP.Types hiding (Header, ResponseHeaders)
36+import Network.Socket (SockAddr)
37+import Network.Wai (Application, Request, Response,
38+ httpVersion, isSecure,
39+ lazyRequestBody, pathInfo,
40+ rawQueryString, remoteHost,
41+ requestHeaders, requestMethod,
42+ responseLBS, vault)
43+import Web.HttpApiData (FromHttpApiData)
44+import Web.HttpApiData.Internal (parseHeaderMaybe,
45+ parseQueryParamMaybe,
46+ parseUrlPieceMaybe)
47+
4148import Servant.API ((:<|>) (..), (:>), Capture,
42− Delete, Get, Header,
43− IsSecure(..), Patch, Post, Put,
49+ Verb, ReflectMethod(reflectMethod),
50+ IsSecure(..), Header,
4451 QueryFlag, QueryParam, QueryParams,
4552 Raw, RemoteHost, ReqBody, Vault)
4653import Servant.API.ContentTypes (AcceptHeader (..),
@@ -55,8 +62,6 @@ import Servant.Server.Internal.Router
5562import Servant.Server.Internal.RoutingApplication
5663import Servant.Server.Internal.ServantErr
5764
58−import Web.HttpApiData (FromHttpApiData)
59−import Web.HttpApiData.Internal (parseUrlPieceMaybe, parseHeaderMaybe, parseQueryParamMaybe)
6065
6166class HasServer layout where
6267 type ServerT layout (m :: * -> *) :: *
@@ -129,8 +134,7 @@ allowedMethodHead method request = method == methodGet && requestMethod request
129134allowedMethod :: Method -> Request -> Bool
130135allowedMethod method request = allowedMethodHead method request || requestMethod request == method
131136
132−processMethodRouter :: forall a. ConvertibleStrings a B.ByteString
133− => Maybe (a, BL.ByteString) -> Status -> Method
137+processMethodRouter :: Maybe (BL.ByteString, BL.ByteString) -> Status -> Method
134138 -> Maybe [(HeaderName, B.ByteString)]
135139 -> Request -> RouteResult Response
136140processMethodRouter handleA status method headers request = case handleA of
@@ -160,7 +164,7 @@ methodRouter method proxy status action = LeafRouter route'
160164 | pathIsEmpty request =
161165 let accH = fromMaybe ct_wildcard $ lookup hAccept $ requestHeaders request
162166 in runAction (action `addMethodCheck` methodCheck method request
163− `addAcceptCheck` acceptCheck proxy accH
167+ `addAcceptCheck` acceptCheck proxy accH
164168 ) respond $ \ output -> do
165169 let handleA = handleAcceptH proxy (AcceptHeader accH) output
166170 processMethodRouter handleA status method Nothing request
@@ -176,95 +180,33 @@ methodRouterHeaders method proxy status action = LeafRouter route'
176180 | pathIsEmpty request =
177181 let accH = fromMaybe ct_wildcard $ lookup hAccept $ requestHeaders request
178182 in runAction (action `addMethodCheck` methodCheck method request
179− `addAcceptCheck` acceptCheck proxy accH
183+ `addAcceptCheck` acceptCheck proxy accH
180184 ) respond $ \ output -> do
181185 let headers = getHeaders output
182186 handleA = handleAcceptH proxy (AcceptHeader accH) (getResponse output)
183187 processMethodRouter handleA status method (Just headers) request
184188 | otherwise = respond $ Fail err404
185189
186−methodRouterEmpty :: Method
187− -> Delayed (ExceptT ServantErr IO ())
188− -> Router
189−methodRouterEmpty method action = LeafRouter route'
190− where
191− route' request respond
192− | pathIsEmpty request = do
193− runAction (addMethodCheck action (methodCheck method request)) respond $ \ () ->
194− Route $! responseLBS noContent204 [] ""
195− | otherwise = respond $ Fail err404
196−
197−-- | If you have a 'Delete' endpoint in your API,
198−-- the handler for this endpoint is meant to delete
199−-- a resource.
200−--
201−-- The code of the handler will, just like
202−-- for 'Servant.API.Get.Get', 'Servant.API.Post.Post' and
203−-- 'Servant.API.Put.Put', run in @ExceptT ServantErr IO ()@.
204−-- The 'Int' represents the status code and the 'String' a message
205−-- to be returned. You can use 'Control.Monad.Trans.Except.throwE' to
206−-- painlessly error out if the conditions for a successful deletion
207−-- are not met.
208190instance OVERLAPPABLE_
209− ( AllCTRender ctypes a
210− ) => HasServer (Delete ctypes a) where
211−
212− type ServerT (Delete ctypes a) m = m a
213−
214− route Proxy = methodRouter methodDelete (Proxy :: Proxy ctypes) ok200
191+ ( AllCTRender ctypes a, ReflectMethod method, KnownNat status
192+ ) => HasServer (Verb method status ctypes a) where
215193
216−instance OVERLAPPING_
217− HasServer (Delete ctypes ()) where
218−
219− type ServerT (Delete ctypes ()) m = m ()
194+ type ServerT (Verb method status ctypes a) m = m a
220195
221− route Proxy = methodRouterEmpty methodDelete
196+ route Proxy = methodRouter method (Proxy :: Proxy ctypes) status
197+ where method = reflectMethod (Proxy :: Proxy method)
198+ status = toEnum . fromInteger $ natVal (Proxy :: Proxy status)
222199
223−-- Add response headers
224200instance OVERLAPPING_
225− ( GetHeaders (Headers h v), AllCTRender ctypes v
226− ) => HasServer (Delete ctypes (Headers h v)) where
227−
228− type ServerT (Delete ctypes (Headers h v)) m = m (Headers h v)
229−
230− route Proxy = methodRouterHeaders methodDelete (Proxy :: Proxy ctypes) ok200
201+ ( AllCTRender ctypes a, ReflectMethod method, KnownNat status
202+ , GetHeaders (Headers h a)
203+ ) => HasServer (Verb method status ctypes (Headers h a)) where
231204
232−-- | When implementing the handler for a 'Get' endpoint,
233−-- just like for 'Servant.API.Delete.Delete', 'Servant.API.Post.Post'
234−-- and 'Servant.API.Put.Put', the handler code runs in the
235−-- @ExceptT ServantErr IO@ monad, where the 'Int' represents
236−-- the status code and the 'String' a message, returned in case of
237−-- failure. You can quite handily use 'Control.Monad.Trans.Except.throwE'
238−-- to quickly fail if some conditions are not met.
239−--
240−-- If successfully returning a value, we use the type-level list, combined
241−-- with the request's @Accept@ header, to encode the value for you
242−-- (returning a status code of 200). If there was no @Accept@ header or it
243−-- was @*\/\*@, we return encode using the first @Content-Type@ type on the
244−-- list.
245−instance OVERLAPPABLE_
246− ( AllCTRender ctypes a ) => HasServer (Get ctypes a) where
205+ type ServerT (Verb method status ctypes (Headers h a)) m = m (Headers h a)
247206
248− type ServerT (Get ctypes a) m = m a
249−
250− route Proxy = methodRouter methodGet (Proxy :: Proxy ctypes) ok200
251−
252−-- '()' ==> 204 No Content
253−instance OVERLAPPING_
254− HasServer (Get ctypes ()) where
255−
256− type ServerT (Get ctypes ()) m = m ()
257−
258− route Proxy = methodRouterEmpty methodGet
259−
260−-- Add response headers
261−instance OVERLAPPING_
262− ( GetHeaders (Headers h v), AllCTRender ctypes v
263− ) => HasServer (Get ctypes (Headers h v)) where
264−
265− type ServerT (Get ctypes (Headers h v)) m = m (Headers h v)
266−
267− route Proxy = methodRouterHeaders methodGet (Proxy :: Proxy ctypes) ok200
207+ route Proxy = methodRouterHeaders method (Proxy :: Proxy ctypes) status
208+ where method = reflectMethod (Proxy :: Proxy method)
209+ status = toEnum . fromInteger $ natVal (Proxy :: Proxy status)
268210
269211-- | If you use 'Header' in one of the endpoints for your API,
270212-- this automatically requires your server-side handler to be a function
@@ -297,113 +239,6 @@ instance (KnownSymbol sym, FromHttpApiData a, HasServer sublayout)
297239 in route (Proxy :: Proxy sublayout) (passToServer subserver mheader)
298240 where str = fromString $ symbolVal (Proxy :: Proxy sym)
299241
300−-- | When implementing the handler for a 'Post' endpoint,
301−-- just like for 'Servant.API.Delete.Delete', 'Servant.API.Get.Get'
302−-- and 'Servant.API.Put.Put', the handler code runs in the
303−-- @ExceptT ServantErr IO@ monad, where the 'Int' represents
304−-- the status code and the 'String' a message, returned in case of
305−-- failure. You can quite handily use 'Control.Monad.Trans.Except.throwE'
306−-- to quickly fail if some conditions are not met.
307−--
308−-- If successfully returning a value, we use the type-level list, combined
309−-- with the request's @Accept@ header, to encode the value for you
310−-- (returning a status code of 201). If there was no @Accept@ header or it
311−-- was @*\/\*@, we return encode using the first @Content-Type@ type on the
312−-- list.
313−instance OVERLAPPABLE_
314− ( AllCTRender ctypes a
315− ) => HasServer (Post ctypes a) where
316−
317− type ServerT (Post ctypes a) m = m a
318−
319− route Proxy = methodRouter methodPost (Proxy :: Proxy ctypes) created201
320−
321−instance OVERLAPPING_
322− HasServer (Post ctypes ()) where
323−
324− type ServerT (Post ctypes ()) m = m ()
325−
326− route Proxy = methodRouterEmpty methodPost
327−
328−-- Add response headers
329−instance OVERLAPPING_
330− ( GetHeaders (Headers h v), AllCTRender ctypes v
331− ) => HasServer (Post ctypes (Headers h v)) where
332−
333− type ServerT (Post ctypes (Headers h v)) m = m (Headers h v)
334−
335− route Proxy = methodRouterHeaders methodPost (Proxy :: Proxy ctypes) created201
336−
337−-- | When implementing the handler for a 'Put' endpoint,
338−-- just like for 'Servant.API.Delete.Delete', 'Servant.API.Get.Get'
339−-- and 'Servant.API.Post.Post', the handler code runs in the
340−-- @ExceptT ServantErr IO@ monad, where the 'Int' represents
341−-- the status code and the 'String' a message, returned in case of
342−-- failure. You can quite handily use 'Control.Monad.Trans.Except.throwE'
343−-- to quickly fail if some conditions are not met.
344−--
345−-- If successfully returning a value, we use the type-level list, combined
346−-- with the request's @Accept@ header, to encode the value for you
347−-- (returning a status code of 200). If there was no @Accept@ header or it
348−-- was @*\/\*@, we return encode using the first @Content-Type@ type on the
349−-- list.
350−instance OVERLAPPABLE_
351− ( AllCTRender ctypes a) => HasServer (Put ctypes a) where
352−
353− type ServerT (Put ctypes a) m = m a
354−
355− route Proxy = methodRouter methodPut (Proxy :: Proxy ctypes) ok200
356−
357−instance OVERLAPPING_
358− HasServer (Put ctypes ()) where
359−
360− type ServerT (Put ctypes ()) m = m ()
361−
362− route Proxy = methodRouterEmpty methodPut
363−
364−-- Add response headers
365−instance OVERLAPPING_
366− ( GetHeaders (Headers h v), AllCTRender ctypes v
367− ) => HasServer (Put ctypes (Headers h v)) where
368−
369− type ServerT (Put ctypes (Headers h v)) m = m (Headers h v)
370−
371− route Proxy = methodRouterHeaders methodPut (Proxy :: Proxy ctypes) ok200
372−
373−-- | When implementing the handler for a 'Patch' endpoint,
374−-- just like for 'Servant.API.Delete.Delete', 'Servant.API.Get.Get'
375−-- and 'Servant.API.Put.Put', the handler code runs in the
376−-- @ExceptT ServantErr IO@ monad, where the 'Int' represents
377−-- the status code and the 'String' a message, returned in case of
378−-- failure. You can quite handily use 'Control.Monad.Trans.Except.throwE'
379−-- to quickly fail if some conditions are not met.
380−--
381−-- If successfully returning a value, we just require that its type has
382−-- a 'ToJSON' instance and servant takes care of encoding it for you,
383−-- yielding status code 200 along the way.
384−instance OVERLAPPABLE_
385− ( AllCTRender ctypes a) => HasServer (Patch ctypes a) where
386−
387− type ServerT (Patch ctypes a) m = m a
388−
389− route Proxy = methodRouter methodPatch (Proxy :: Proxy ctypes) ok200
390−
391−instance OVERLAPPING_
392− HasServer (Patch ctypes ()) where
393−
394− type ServerT (Patch ctypes ()) m = m ()
395−
396− route Proxy = methodRouterEmpty methodPatch
397−
398−-- Add response headers
399−instance OVERLAPPING_
400− ( GetHeaders (Headers h v), AllCTRender ctypes v
401− ) => HasServer (Patch ctypes (Headers h v)) where
402−
403− type ServerT (Patch ctypes (Headers h v)) m = m (Headers h v)
404−
405− route Proxy = methodRouterHeaders methodPatch (Proxy :: Proxy ctypes) ok200
406−
407242-- | If you use @'QueryParam' "author" Text@ in one of the endpoints for your API,
408243-- this automatically requires your server-side handler to be a function
409244-- that takes an argument of type @'Maybe' 'Text'@.
servant-server/test/Servant/Server/ErrorSpec.hs+1−1
@@ -162,7 +162,7 @@ errorRetrySpec = describe "Handler search"
162162
163163 it "should continue when URLs don't match" $ do
164164 request methodPost "" [jsonCT, jsonAccept] jsonBody
165− `shouldRespondWith` 201 { matchBody = Just $ encode (7 :: Int) }
165+ `shouldRespondWith` 200 { matchBody = Just $ encode (7 :: Int) }
166166
167167 it "should continue when methods don't match" $ do
168168 request methodGet "a" [jsonCT, jsonAccept] jsonBody
servant-server/test/Servant/Server/Internal/EnterSpec.hs+1−1
@@ -52,7 +52,7 @@ enterSpec = describe "Enter" $ do
5252
5353 it "allows running arbitrary monads" $ do
5454 get "int" `shouldRespondWith` "1797"
55− post "string" "3" `shouldRespondWith` "\"hi\""{ matchStatus = 201 }
55+ post "string" "3" `shouldRespondWith` "\"hi\""{ matchStatus = 200 }
5656
5757 with (return (serve combinedAPI combinedReaderServer)) $ do
5858 it "allows combnation of enters" $ do
servant-server/test/Servant/ServerSpec.hs+226−252
@@ -3,8 +3,10 @@
33{-# LANGUAGE DeriveGeneric #-}
44{-# LANGUAGE FlexibleInstances #-}
55{-# LANGUAGE OverloadedStrings #-}
6+{-# LANGUAGE PolyKinds #-}
67{-# LANGUAGE ScopedTypeVariables #-}
78{-# LANGUAGE TypeOperators #-}
9+{-# LANGUAGE TypeFamilies #-}
810{-# LANGUAGE TypeSynonymInstances #-}
911{-# LANGUAGE FlexibleInstances #-}
1012
@@ -13,7 +15,7 @@ module Servant.ServerSpec where
1315#if !MIN_VERSION_base(4,8,0)
1416import Control.Applicative ((<$>))
1517#endif
16−import Control.Monad (forM_, when)
18+import Control.Monad (forM_, when, unless)
1719import Control.Monad.Trans.Except (ExceptT, throwE)
1820import Data.Aeson (FromJSON, ToJSON, decode', encode)
1921import Data.ByteString.Conversion ()
@@ -23,82 +25,144 @@ import Data.String (fromString)
2325import Data.String.Conversions (cs)
2426import qualified Data.Text as T
2527import GHC.Generics (Generic)
26−import Network.HTTP.Types (hAccept, hContentType,
27− methodDelete, methodGet, methodHead,
28− methodPatch, methodPost, methodPut,
29− ok200, parseQuery, Status(..))
28+import Network.HTTP.Types (Status (..), hAccept, hContentType,
29+ methodDelete, methodGet,
30+ methodHead, methodPatch,
31+ methodPost, methodPut, ok200,
32+ parseQuery)
3033import Network.Wai (Application, Request, pathInfo,
3134 queryString, rawQueryString,
32− responseLBS, responseBuilder)
33−import Network.Wai.Internal (Response(ResponseBuilder))
35+ responseBuilder, responseLBS)
36+import Network.Wai.Internal (Response (ResponseBuilder))
3437import Network.Wai.Test (defaultRequest, request,
35− runSession, simpleBody)
38+ runSession, simpleBody,
39+ simpleHeaders, simpleStatus)
3640import Servant.API ((:<|>) (..), (:>), Capture, Delete,
37− Get, Header (..), Headers,
38− HttpVersion, IsSecure (..), JSON,
39− Patch, PlainText, Post, Put,
41+ Get, Header (..),
42+ Headers, HttpVersion,
43+ IsSecure (..), JSON,
44+ NoContent (..), Patch, PlainText,
45+ Post, Put,
4046 QueryFlag, QueryParam, QueryParams,
4147 Raw, RemoteHost, ReqBody,
42− addHeader)
43−import Servant.Server (Server, serve, ServantErr(..), err404)
44−import Test.Hspec (Spec, describe, it, shouldBe)
48+ StdMethod (..), Verb, addHeader)
49+import Servant.Server (ServantErr (..), Server, err404,
50+ serve)
51+import Test.Hspec (Spec, context, describe, it,
52+ shouldBe, shouldContain)
4553import Test.Hspec.Wai (get, liftIO, matchHeaders,
46− matchStatus, post, request,
54+ matchStatus, request,
4755 shouldRespondWith, with, (<:>))
48−import Servant.Server.Internal.RoutingApplication (toApplication, RouteResult(..))
56+
57+import Servant.Server.Internal.RoutingApplication
58+ (toApplication, RouteResult(..))
4959import Servant.Server.Internal.Router
5060 (tweakResponse, runRouter,
5161 Router, Router'(LeafRouter))
5262
5363
54−-- * test data types
55−
56−data Person = Person {
57− name :: String,
58− age :: Integer
59− }
60− deriving (Eq, Show, Generic)
61−
62−instance ToJSON Person
63−instance FromJSON Person
64−
65−alice :: Person
66−alice = Person "Alice" 42
67−
68−data Animal = Animal {
69− species :: String,
70− numberOfLegs :: Integer
71− }
72− deriving (Eq, Show, Generic)
73−
74−instance ToJSON Animal
75−instance FromJSON Animal
76−
77−jerry :: Animal
78−jerry = Animal "Mouse" 4
79−
80−tweety :: Animal
81−tweety = Animal "Bird" 2
82−
83−
84−-- * specs
64+-- * Specs
8565
8666spec :: Spec
8767spec = do
68+ verbSpec
8869 captureSpec
89− getSpec
90− headSpec
91− postSpec
92− putSpec
93− patchSpec
9470 queryParamSpec
71+ reqBodySpec
9572 headerSpec
9673 rawSpec
97− unionSpec
98− routerSpec
74+ alternativeSpec
9975 responseHeadersSpec
100− miscReqCombinatorsSpec
101−
76+ routerSpec
77+ miscCombinatorSpec
78+
79+------------------------------------------------------------------------------
80+-- * verbSpec {{{
81+------------------------------------------------------------------------------
82+
83+type VerbApi method status
84+ = Verb method status '[JSON] Person
85+ :<|> "noContent" :> Verb method status '[JSON] NoContent
86+ :<|> "header" :> Verb method status '[JSON] (Headers '[Header "H" Int] Person)
87+ :<|> "headerNC" :> Verb method status '[JSON] (Headers '[Header "H" Int] NoContent)
88+
89+verbSpec :: Spec
90+verbSpec = describe "Servant.API.Verb" $ do
91+ let server :: Server (VerbApi method status)
92+ server = return alice
93+ :<|> return NoContent
94+ :<|> return (addHeader 5 alice)
95+ :<|> return (addHeader 10 NoContent)
96+ get200 = Proxy :: Proxy (VerbApi 'GET 200)
97+ post210 = Proxy :: Proxy (VerbApi 'POST 210)
98+ put203 = Proxy :: Proxy (VerbApi 'PUT 203)
99+ delete280 = Proxy :: Proxy (VerbApi 'DELETE 280)
100+ patch214 = Proxy :: Proxy (VerbApi 'PATCH 214)
101+ wrongMethod m = if m == methodPatch then methodPost else methodPatch
102+ test desc api method (status :: Int) = context desc $
103+
104+ with (return $ serve api server) $ do
105+
106+ -- HEAD and 214/215 need not return bodies
107+ unless (status `elem` [214, 215] || method == methodHead) $
108+ it "returns the person" $ do
109+ response <- Test.Hspec.Wai.request method "/" [] ""
110+ liftIO $ statusCode (simpleStatus response) `shouldBe` status
111+ liftIO $ decode' (simpleBody response) `shouldBe` Just alice
112+
113+ it "returns no content on NoContent" $ do
114+ response <- Test.Hspec.Wai.request method "/noContent" [] ""
115+ liftIO $ statusCode (simpleStatus response) `shouldBe` status
116+ liftIO $ simpleBody response `shouldBe` ""
117+
118+ -- HEAD should not return body
119+ when (method == methodHead) $
120+ it "HEAD returns no content body" $ do
121+ response <- Test.Hspec.Wai.request method "/" [] ""
122+ liftIO $ simpleBody response `shouldBe` ""
123+
124+ it "throws 405 on wrong method " $ do
125+ Test.Hspec.Wai.request (wrongMethod method) "/" [] ""
126+ `shouldRespondWith` 405
127+
128+ it "returns headers" $ do
129+ response1 <- Test.Hspec.Wai.request method "/header" [] ""
130+ liftIO $ statusCode (simpleStatus response1) `shouldBe` status
131+ liftIO $ simpleHeaders response1 `shouldContain` [("H", "5")]
132+
133+ response2 <- Test.Hspec.Wai.request method "/header" [] ""
134+ liftIO $ statusCode (simpleStatus response2) `shouldBe` status
135+ liftIO $ simpleHeaders response2 `shouldContain` [("H", "5")]
136+
137+ it "handles trailing '/' gracefully" $ do
138+ response <- Test.Hspec.Wai.request method "/headerNC/" [] ""
139+ liftIO $ statusCode (simpleStatus response) `shouldBe` status
140+
141+ it "returns 406 if the Accept header is not supported" $ do
142+ Test.Hspec.Wai.request method "" [(hAccept, "crazy/mime")] ""
143+ `shouldRespondWith` 406
144+
145+ it "responds if the Accept header is supported" $ do
146+ response <- Test.Hspec.Wai.request method ""
147+ [(hAccept, "application/json")] ""
148+ liftIO $ statusCode (simpleStatus response) `shouldBe` status
149+
150+ it "sets the Content-Type header" $ do
151+ response <- Test.Hspec.Wai.request method "" [] ""
152+ liftIO $ simpleHeaders response `shouldContain`
153+ [("Content-Type", "application/json")]
154+
155+ test "GET 200" get200 methodGet 200
156+ test "POST 210" post210 methodPost 210
157+ test "PUT 203" put203 methodPut 203
158+ test "DELETE 280" delete280 methodDelete 280
159+ test "PATCH 214" patch214 methodPatch 214
160+ test "GET 200 with HEAD" get200 methodHead 200
161+
162+-- }}}
163+------------------------------------------------------------------------------
164+-- * captureSpec {{{
165+------------------------------------------------------------------------------
102166
103167type CaptureApi = Capture "legs" Integer :> Get '[JSON] Animal
104168captureApi :: Proxy CaptureApi
@@ -128,63 +192,10 @@ captureSpec = do
128192 it "strips the captured path snippet from pathInfo" $ do
129193 get "/captured/foo" `shouldRespondWith` (fromString (show ["foo" :: String]))
130194
131−
132−type GetApi = Get '[JSON] Person
133− :<|> "empty" :> Get '[] ()
134− :<|> "post" :> Post '[] ()
135−getApi :: Proxy GetApi
136−getApi = Proxy
137−
138−getSpec :: Spec
139−getSpec = do
140− describe "Servant.API.Get" $ do
141− let server = return alice :<|> return () :<|> return ()
142− with (return $ serve getApi server) $ do
143−
144− it "allows to GET a Person" $ do
145− response <- get "/"
146− return response `shouldRespondWith` 200
147− liftIO $ decode' (simpleBody response) `shouldBe` Just alice
148−
149− it "throws 405 (wrong method) on POSTs" $ do
150− post "/" "" `shouldRespondWith` 405
151− post "/empty" "" `shouldRespondWith` 405
152−
153− it "returns 204 if the type is '()'" $ do
154− get "/empty" `shouldRespondWith` ""{ matchStatus = 204 }
155−
156− it "returns 406 if the Accept header is not supported" $ do
157− Test.Hspec.Wai.request methodGet "" [(hAccept, "crazy/mime")] ""
158− `shouldRespondWith` 406
159−
160−
161−headSpec :: Spec
162−headSpec = do
163− describe "Servant.API.Head" $ do
164− let server = return alice :<|> return () :<|> return ()
165− with (return $ serve getApi server) $ do
166−
167− it "allows to GET a Person" $ do
168− response <- Test.Hspec.Wai.request methodHead "/" [] ""
169− return response `shouldRespondWith` 200
170− liftIO $ decode' (simpleBody response) `shouldBe` (Nothing :: Maybe Person)
171−
172− it "does not allow HEAD to POST route" $ do
173− response <- Test.Hspec.Wai.request methodHead "/post" [] ""
174− return response `shouldRespondWith` 405
175−
176− it "throws 405 (wrong method) on POSTs" $ do
177− post "/" "" `shouldRespondWith` 405
178− post "/empty" "" `shouldRespondWith` 405
179−
180− it "returns 204 if the type is '()'" $ do
181− response <- Test.Hspec.Wai.request methodHead "/empty" [] ""
182− return response `shouldRespondWith` ""{ matchStatus = 204 }
183−
184− it "returns 406 if the Accept header is not supported" $ do
185− Test.Hspec.Wai.request methodHead "" [(hAccept, "crazy/mime")] ""
186− `shouldRespondWith` 406
187−
195+-- }}}
196+------------------------------------------------------------------------------
197+-- * queryParamSpec {{{
198+------------------------------------------------------------------------------
188199
189200type QueryParamApi = QueryParam "name" String :> Get '[JSON] Person
190201 :<|> "a" :> QueryParams "names" String :> Get '[JSON] Person
@@ -269,131 +280,41 @@ queryParamSpec = do
269280 name = "Alice"
270281 }
271282
272−type PostApi =
273− ReqBody '[JSON] Person :> Post '[JSON] Integer
274− :<|> "bla" :> ReqBody '[JSON] Person :> Post '[JSON] Integer
275− :<|> "empty" :> Post '[] ()
276−
277−postApi :: Proxy PostApi
278−postApi = Proxy
279−
280−postSpec :: Spec
281−postSpec = do
282− describe "Servant.API.Post and .ReqBody" $ do
283− let server = return . age :<|> return . age :<|> return ()
284− with (return $ serve postApi server) $ do
285− let post' x = Test.Hspec.Wai.request methodPost x [(hContentType
286− , "application/json;charset=utf-8")]
287−
288− it "allows to POST a Person" $ do
289− post' "/" (encode alice) `shouldRespondWith` "42"{
290− matchStatus = 201
291− }
292−
293− it "allows alternative routes if all have request bodies" $ do
294− post' "/bla" (encode alice) `shouldRespondWith` "42"{
295− matchStatus = 201
296− }
297−
298− it "handles trailing '/' gracefully" $ do
299− post' "/bla/" (encode alice) `shouldRespondWith` "42"{
300− matchStatus = 201
301− }
302−
303− it "correctly rejects invalid request bodies with status 400" $ do
304− post' "/" "some invalid body" `shouldRespondWith` 400
305−
306− it "returns 204 if the type is '()'" $ do
307− post' "empty" "" `shouldRespondWith` ""{ matchStatus = 204 }
308−
309− it "responds with 415 if the request body media type is unsupported" $ do
310− let post'' x = Test.Hspec.Wai.request methodPost x [(hContentType
311− , "application/nonsense")]
312− post'' "/" "anything at all" `shouldRespondWith` 415
313−
314−type PutApi =
315− ReqBody '[JSON] Person :> Put '[JSON] Integer
316− :<|> "bla" :> ReqBody '[JSON] Person :> Put '[JSON] Integer
317− :<|> "empty" :> Put '[] ()
318−
319−putApi :: Proxy PutApi
320−putApi = Proxy
321−
322−putSpec :: Spec
323−putSpec = do
324− describe "Servant.API.Put and .ReqBody" $ do
325− let server = return . age :<|> return . age :<|> return ()
326− with (return $ serve putApi server) $ do
327− let put' x = Test.Hspec.Wai.request methodPut x [(hContentType
328− , "application/json;charset=utf-8")]
283+-- }}}
284+------------------------------------------------------------------------------
285+-- * reqBodySpec {{{
286+------------------------------------------------------------------------------
287+type ReqBodyApi = ReqBody '[JSON] Person :> Post '[JSON] Person
288+ :<|> "blah" :> ReqBody '[JSON] Person :> Put '[JSON] Integer
329289
330− it "allows to put a Person" $ do
331− put' "/" (encode alice) `shouldRespondWith` "42"{
332− matchStatus = 200
333− }
334−
335− it "allows alternative routes if all have request bodies" $ do
336− put' "/bla" (encode alice) `shouldRespondWith` "42"{
337− matchStatus = 200
338− }
290+reqBodyApi :: Proxy ReqBodyApi
291+reqBodyApi = Proxy
339292
340− it "handles trailing '/' gracefully" $ do
341− put' "/bla/" (encode alice) `shouldRespondWith` "42"{
342− matchStatus = 200
343− }
293+reqBodySpec :: Spec
294+reqBodySpec = describe "Servant.API.ReqBody" $ do
344295
345− it "correctly rejects invalid request bodies with status 400" $ do
346− put' "/" "some invalid body" `shouldRespondWith` 400
296+ let server :: Server ReqBodyApi
297+ server = return :<|> return . age
298+ mkReq method x = Test.Hspec.Wai.request method x
299+ [(hContentType, "application/json;charset=utf-8")]
347300
348− it "returns 204 if the type is '()'" $ do
349− put' "empty" "" `shouldRespondWith` ""{ matchStatus = 204 }
301+ with (return $ serve reqBodyApi server) $ do
350302
351− it "responds with 415 if the request body media type is unsupported" $ do
352− let put'' x = Test.Hspec.Wai.request methodPut x [(hContentType
353− , "application/nonsense")]
354− put'' "/" "anything at all" `shouldRespondWith` 415
303+ it "passes the argument to the handler" $ do
304+ response <- mkReq methodPost "" (encode alice)
305+ liftIO $ decode' (simpleBody response) `shouldBe` Just alice
355306
356−type PatchApi =
357− ReqBody '[JSON] Person :> Patch '[JSON] Integer
358− :<|> "bla" :> ReqBody '[JSON] Person :> Patch '[JSON] Integer
359− :<|> "empty" :> Patch '[] ()
307+ it "rejects invalid request bodies with status 400" $ do
308+ mkReq methodPut "/blah" "some invalid body" `shouldRespondWith` 400
360309
361−patchApi :: Proxy PatchApi
362−patchApi = Proxy
310+ it "responds with 415 if the request body media type is unsupported" $ do
311+ Test.Hspec.Wai.request methodPost "/"
312+ [(hContentType, "application/nonsense")] "" `shouldRespondWith` 415
363313
364−patchSpec :: Spec
365−patchSpec = do
366− describe "Servant.API.Patch and .ReqBody" $ do
367− let server = return . age :<|> return . age :<|> return ()
368− with (return $ serve patchApi server) $ do
369− let patch' x = Test.Hspec.Wai.request methodPatch x [(hContentType
370− , "application/json;charset=utf-8")]
371−
372− it "allows to patch a Person" $ do
373− patch' "/" (encode alice) `shouldRespondWith` "42"{
374− matchStatus = 200
375− }
376−
377− it "allows alternative routes if all have request bodies" $ do
378− patch' "/bla" (encode alice) `shouldRespondWith` "42"{
379− matchStatus = 200
380− }
381−
382− it "handles trailing '/' gracefully" $ do
383− patch' "/bla/" (encode alice) `shouldRespondWith` "42"{
384− matchStatus = 200
385− }
386−
387− it "correctly rejects invalid request bodies with status 400" $ do
388− patch' "/" "some invalid body" `shouldRespondWith` 400
389−
390− it "returns 204 if the type is '()'" $ do
391− patch' "empty" "" `shouldRespondWith` ""{ matchStatus = 204 }
392−
393− it "responds with 415 if the request body media type is unsupported" $ do
394− let patch'' x = Test.Hspec.Wai.request methodPatch x [(hContentType
395− , "application/nonsense")]
396− patch'' "/" "anything at all" `shouldRespondWith` 415
314+-- }}}
315+------------------------------------------------------------------------------
316+-- * headerSpec {{{
317+------------------------------------------------------------------------------
397318
398319type HeaderApi a = Header "MyHeader" a :> Delete '[JSON] ()
399320headerApi :: Proxy (HeaderApi a)
@@ -411,23 +332,30 @@ headerSpec = describe "Servant.API.Header" $ do
411332 expectsString Nothing = error "Expected a string"
412333
413334 with (return (serve headerApi expectsInt)) $ do
414− let delete' x = Test.Hspec.Wai.request methodDelete x [("MyHeader" ,"5")]
335+ let delete' x = Test.Hspec.Wai.request methodDelete x [("MyHeader", "5")]
415336
416337 it "passes the header to the handler (Int)" $
417− delete' "/" "" `shouldRespondWith` 204
338+ delete' "/" "" `shouldRespondWith` 200
418339
419340 with (return (serve headerApi expectsString)) $ do
420− let delete' x = Test.Hspec.Wai.request methodDelete x [("MyHeader" ,"more from you")]
341+ let delete' x = Test.Hspec.Wai.request methodDelete x [("MyHeader", "more from you")]
421342
422343 it "passes the header to the handler (String)" $
423− delete' "/" "" `shouldRespondWith` 204
344+ delete' "/" "" `shouldRespondWith` 200
424345
346+-- }}}
347+------------------------------------------------------------------------------
348+-- * rawSpec {{{
349+------------------------------------------------------------------------------
425350
426351type RawApi = "foo" :> Raw
352+
427353rawApi :: Proxy RawApi
428354rawApi = Proxy
355+
429356rawApplication :: Show a => (Request -> a) -> Application
430−rawApplication f request_ respond = respond $ responseLBS ok200 [] (cs $ show $ f request_)
357+rawApplication f request_ respond = respond $ responseLBS ok200 []
358+ (cs $ show $ f request_)
431359
432360rawSpec :: Spec
433361rawSpec = do
@@ -448,7 +376,10 @@ rawSpec = do
448376 liftIO $ do
449377 simpleBody response `shouldBe` cs (show ["bar" :: String])
450378
451−
379+-- }}}
380+------------------------------------------------------------------------------
381+-- * alternativeSpec {{{
382+------------------------------------------------------------------------------
452383type AlternativeApi =
453384 "foo" :> Get '[JSON] Person
454385 :<|> "bar" :> Get '[JSON] Animal
@@ -456,11 +387,12 @@ type AlternativeApi =
456387 :<|> "bar" :> Post '[JSON] Animal
457388 :<|> "bar" :> Put '[JSON] Animal
458389 :<|> "bar" :> Delete '[JSON] ()
459−unionApi :: Proxy AlternativeApi
460−unionApi = Proxy
461390
462−unionServer :: Server AlternativeApi
463−unionServer =
391+alternativeApi :: Proxy AlternativeApi
392+alternativeApi = Proxy
393+
394+alternativeServer :: Server AlternativeApi
395+alternativeServer =
464396 return alice
465397 :<|> return jerry
466398 :<|> return "a string"
@@ -468,10 +400,10 @@ unionServer =
468400 :<|> return jerry
469401 :<|> return ()
470402
471−unionSpec :: Spec
472−unionSpec = do
403+alternativeSpec :: Spec
404+alternativeSpec = do
473405 describe "Servant.API.Alternative" $ do
474− with (return $ serve unionApi unionServer) $ do
406+ with (return $ serve alternativeApi alternativeServer) $ do
475407
476408 it "unions endpoints" $ do
477409 response <- get "/foo"
@@ -488,7 +420,10 @@ unionSpec = do
488420
489421 it "returns 404 if the path does not exist" $ do
490422 get "/nonexistent" `shouldRespondWith` 404
491−
423+-- }}}
424+------------------------------------------------------------------------------
425+-- * responseHeaderSpec {{{
426+------------------------------------------------------------------------------
492427type ResponseHeadersApi =
493428 Get '[JSON] (Headers '[Header "H1" Int, Header "H2" String] String)
494429 :<|> Post '[JSON] (Headers '[Header "H1" Int, Header "H2" String] String)
@@ -505,26 +440,29 @@ responseHeadersSpec :: Spec
505440responseHeadersSpec = describe "ResponseHeaders" $ do
506441 with (return $ serve (Proxy :: Proxy ResponseHeadersApi) responseHeadersServer) $ do
507442
508− let methods = [(methodGet, 200), (methodPost, 201), (methodPut, 200), (methodPatch, 200)]
443+ let methods = [methodGet, methodPost, methodPut, methodPatch]
509444
510445 it "includes the headers in the response" $
511− forM_ methods $ \(method, expected) ->
446+ forM_ methods $ \method ->
512447 Test.Hspec.Wai.request method "/" [] ""
513448 `shouldRespondWith` "\"hi\""{ matchHeaders = ["H1" <:> "5", "H2" <:> "kilroy"]
514− , matchStatus = expected
449+ , matchStatus = 200
515450 }
516451
517452 it "responds with not found for non-existent endpoints" $
518− forM_ methods $ \(method,_) ->
453+ forM_ methods $ \method ->
519454 Test.Hspec.Wai.request method "blahblah" [] ""
520455 `shouldRespondWith` 404
521456
522457 it "returns 406 if the Accept header is not supported" $
523− forM_ methods $ \(method,_) ->
458+ forM_ methods $ \method ->
524459 Test.Hspec.Wai.request method "" [(hAccept, "crazy/mime")] ""
525460 `shouldRespondWith` 406
526461
527−
462+-- }}}
463+------------------------------------------------------------------------------
464+-- * routerSpec {{{
465+------------------------------------------------------------------------------
528466routerSpec :: Spec
529467routerSpec = do
530468 describe "Servant.Server.Internal.Router" $ do
@@ -543,6 +481,10 @@ routerSpec = do
543481 it "calls f on route result" $ do
544482 get "" `shouldRespondWith` 202
545483
484+-- }}}
485+------------------------------------------------------------------------------
486+-- * miscCombinatorSpec {{{
487+------------------------------------------------------------------------------
546488type MiscCombinatorsAPI
547489 = "version" :> HttpVersion :> Get '[JSON] String
548490 :<|> "secure" :> IsSecure :> Get '[JSON] String
@@ -561,8 +503,8 @@ miscServ = versionHandler
561503 secureHandler NotSecure = return "not secure"
562504 hostHandler = return . show
563505
564−miscReqCombinatorsSpec :: Spec
565−miscReqCombinatorsSpec = with (return $ serve miscApi miscServ) $
506+miscCombinatorSpec :: Spec
507+miscCombinatorSpec = with (return $ serve miscApi miscServ) $
566508 describe "Misc. combinators for request inspection" $ do
567509 it "Successfully gets the HTTP version specified in the request" $
568510 go "/version" "\"HTTP/1.0\""
@@ -574,3 +516,35 @@ miscReqCombinatorsSpec = with (return $ serve miscApi miscServ) $
574516 go "/host" "\"0.0.0.0:0\""
575517
576518 where go path res = Test.Hspec.Wai.get path `shouldRespondWith` res
519+-- }}}
520+------------------------------------------------------------------------------
521+-- * Test data types {{{
522+------------------------------------------------------------------------------
523+
524+data Person = Person {
525+ name :: String,
526+ age :: Integer
527+ }
528+ deriving (Eq, Show, Generic)
529+
530+instance ToJSON Person
531+instance FromJSON Person
532+
533+alice :: Person
534+alice = Person "Alice" 42
535+
536+data Animal = Animal {
537+ species :: String,
538+ numberOfLegs :: Integer
539+ }
540+ deriving (Eq, Show, Generic)
541+
542+instance ToJSON Animal
543+instance FromJSON Animal
544+
545+jerry :: Animal
546+jerry = Animal "Mouse" 4
547+
548+tweety :: Animal
549+tweety = Animal "Bird" 2
550+-- }}}
servant-server/test/Servant/Utils/StaticFilesSpec.hs+1−6
@@ -15,12 +15,7 @@ import System.IO.Temp (withSystemTempDirectory)
1515import Test.Hspec (Spec, around_, describe, it)
1616import Test.Hspec.Wai (get, shouldRespondWith, with)
1717
18−import Servant.API (JSON)
19−import Servant.API.Alternative ((:<|>) ((:<|>)))
20−import Servant.API.Capture (Capture)
21−import Servant.API.Get (Get)
22−import Servant.API.Raw (Raw)
23−import Servant.API.Sub ((:>))
18+import Servant.API ((:<|>) ((:<|>)), Capture, Get, Raw, (:>), JSON)
2419import Servant.Server (Server, serve)
2520import Servant.ServerSpec (Person (Person))
2621import Servant.Utils.StaticFiles (serveDirectory)
servant/CHANGELOG.md+2
@@ -7,6 +7,8 @@ HEAD
77* Use `http-api-data` instead of `Servant.Common.Text`
88* Remove matrix params.
99* Add PlainText String MimeRender and MimeUnrender instances.
10+* Add new `Verbs` combinator, and make all existing and new verb combinators
11+type synonyms of it.
1012
11130.4.2
1214-----
servant/servant.cabal+1−5
@@ -29,14 +29,9 @@ library
2929 Servant.API.Alternative
3030 Servant.API.Capture
3131 Servant.API.ContentTypes
32− Servant.API.Delete
33− Servant.API.Get
3432 Servant.API.Header
3533 Servant.API.HttpVersion
3634 Servant.API.IsSecure
37− Servant.API.Patch
38− Servant.API.Post
39− Servant.API.Put
4035 Servant.API.QueryParam
4136 Servant.API.Raw
4237 Servant.API.RemoteHost
@@ -44,6 +39,7 @@ library
4439 Servant.API.ResponseHeaders
4540 Servant.API.Sub
4641 Servant.API.Vault
42+ Servant.API.Verbs
4743 Servant.Utils.Links
4844 build-depends:
4945 base >=4.7 && <5
servant/src/Servant/API.hs+22−18
@@ -25,16 +25,7 @@ module Servant.API (
2525 -- | Access the location for arbitrary data to be shared by applications and middleware
2626
2727 -- * Actual endpoints, distinguished by HTTP method
28− module Servant.API.Get,
29− -- | @GET@ requests
30− module Servant.API.Post,
31− -- | @POST@ requests
32− module Servant.API.Delete,
33− -- | @DELETE@ requests
34− module Servant.API.Put,
35− -- | @PUT@ requests
36− module Servant.API.Patch,
37− -- | @PATCH@ requests
28+ module Servant.API.Verbs,
3829
3930 -- * Content Types
4031 module Servant.API.ContentTypes,
@@ -61,17 +52,12 @@ import Servant.API.Alternative ((:<|>) (..))
6152import Servant.API.Capture (Capture)
6253import Servant.API.ContentTypes (Accept (..), FormUrlEncoded,
6354 FromFormUrlEncoded (..), JSON,
64− MimeRender (..),
55+ MimeRender (..), NoContent (NoContent),
6556 MimeUnrender (..), OctetStream,
6657 PlainText, ToFormUrlEncoded (..))
67−import Servant.API.Delete (Delete)
68−import Servant.API.Get (Get)
6958import Servant.API.Header (Header (..))
7059import Servant.API.HttpVersion (HttpVersion (..))
7160import Servant.API.IsSecure (IsSecure (..))
72−import Servant.API.Patch (Patch)
73−import Servant.API.Post (Post)
74−import Servant.API.Put (Put)
7561import Servant.API.QueryParam (QueryFlag, QueryParam,
7662 QueryParams)
7763import Servant.API.Raw (Raw)
@@ -84,7 +70,25 @@ import Servant.API.ResponseHeaders (AddHeader (addHeader),
8470 getHeadersHList, getResponse)
8571import Servant.API.Sub ((:>))
8672import Servant.API.Vault (Vault)
87−import Web.HttpApiData (FromHttpApiData (..), ToHttpApiData (..))
73+import Servant.API.Verbs (PostCreated, Delete, DeleteAccepted,
74+ DeleteNoContent,
75+ DeleteNonAuthoritative, Get,
76+ GetAccepted, GetNoContent,
77+ GetNonAuthoritative,
78+ GetPartialContent,
79+ GetResetContent,
80+ Patch,
81+ PatchAccepted, PatchNoContent,
82+ PatchNoContent,
83+ PatchNonAuthoritative, Post,
84+ PostAccepted, PostNoContent,
85+ PostNonAuthoritative,
86+ PostResetContent, Put,
87+ PutAccepted, PutNoContent,
88+ PutNoContent, PutNonAuthoritative,
89+ ReflectMethod (reflectMethod),
90+ Verb, StdMethod(..))
8891import Servant.Utils.Links (HasLink (..), IsElem, IsElem',
8992 URI (..), safeLink)
90−
93+import Web.HttpApiData (FromHttpApiData (..),
94+ ToHttpApiData (..))
servant/src/Servant/API/ContentTypes.hs+38−23
@@ -2,6 +2,7 @@
22{-# LANGUAGE ConstraintKinds #-}
33{-# LANGUAGE DataKinds #-}
44{-# LANGUAGE DeriveDataTypeable #-}
5+{-# LANGUAGE DeriveGeneric #-}
56{-# LANGUAGE FlexibleInstances #-}
67{-# LANGUAGE MultiParamTypeClasses #-}
78{-# LANGUAGE OverloadedStrings #-}
@@ -12,6 +13,8 @@
1213{-# LANGUAGE UndecidableInstances #-}
1314{-# OPTIONS_HADDOCK not-home #-}
1415
16+#include "overlapping-compat.h"
17+
1518-- | A collection of basic Content-Types (also known as Internet Media
1619-- Types, or MIME types). Additionally, this module provides classes that
1720-- encapsulate how to serialize or deserialize values to or from
@@ -19,7 +22,7 @@
1922--
2023-- Content-Types are used in `ReqBody` and the method combinators:
2124--
22−-- >>> type MyEndpoint = ReqBody '[JSON, PlainText] Book :> Get '[JSON, PlainText] :> Book
25+-- >>> type MyEndpoint = ReqBody '[JSON, PlainText] Book :> Get '[JSON, PlainText] Book
2326--
2427-- Meaning the endpoint accepts requests of Content-Type @application/json@
2528-- or @text/plain;charset-utf8@, and returns data in either one of those
@@ -53,6 +56,9 @@ module Servant.API.ContentTypes
5356 , MimeRender(..)
5457 , MimeUnrender(..)
5558
59+ -- * NoContent
60+ , NoContent(..)
61+
5662 -- * Internal
5763 , AcceptHeader(..)
5864 , AllCTRender(..)
@@ -62,7 +68,6 @@ module Servant.API.ContentTypes
6268 , AllMimeUnrender(..)
6369 , FromFormUrlEncoded(..)
6470 , ToFormUrlEncoded(..)
65− , IsNonEmpty
6671 , eitherDecodeLenient
6772 , canHandleAcceptH
6873 ) where
@@ -72,8 +77,7 @@ import Control.Applicative ((*>), (<*))
7277#endif
7378import Control.Arrow (left)
7479import Control.Monad
75−import Data.Aeson (FromJSON, ToJSON, encode,
76− parseJSON)
80+import Data.Aeson (FromJSON(..), ToJSON(..), encode)
7781import Data.Aeson.Parser (value)
7882import Data.Aeson.Types (parseEither)
7983import Data.Attoparsec.ByteString.Char8 (endOfInput, parseOnly,
@@ -91,7 +95,7 @@ import qualified Data.Text.Encoding as TextS
9195import qualified Data.Text.Lazy as TextL
9296import qualified Data.Text.Lazy.Encoding as TextL
9397import Data.Typeable
94−import GHC.Exts (Constraint)
98+import GHC.Generics (Generic)
9599import qualified Network.HTTP.Media as M
96100import Network.URI (escapeURIString,
97101 isUnreserved, unEscapeString)
@@ -137,7 +141,7 @@ instance Accept OctetStream where
137141 contentType _ = "application" M.// "octet-stream"
138142
139143newtype AcceptHeader = AcceptHeader BS.ByteString
140− deriving (Eq, Show)
144+ deriving (Eq, Show, Read, Typeable, Generic)
141145
142146-- * Render (serializing)
143147
@@ -159,19 +163,19 @@ newtype AcceptHeader = AcceptHeader BS.ByteString
159163class Accept ctype => MimeRender ctype a where
160164 mimeRender :: Proxy ctype -> a -> ByteString
161165
162−class (AllMimeRender list a) => AllCTRender (list :: [*]) a where
166+class (AllMime list) => AllCTRender (list :: [*]) a where
163167 -- If the Accept header can be matched, returns (Just) a tuple of the
164168 -- Content-Type and response (serialization of @a@ into the appropriate
165169 -- mimetype).
166170 handleAcceptH :: Proxy list -> AcceptHeader -> a -> Maybe (ByteString, ByteString)
167171
168−instance (AllMimeRender ctyps a, IsNonEmpty ctyps) => AllCTRender ctyps a where
172+instance OVERLAPPABLE_
173+ (AllMimeRender (ct ': cts) a) => AllCTRender (ct ': cts) a where
169174 handleAcceptH _ (AcceptHeader accept) val = M.mapAcceptMedia lkup accept
170− where pctyps = Proxy :: Proxy ctyps
175+ where pctyps = Proxy :: Proxy (ct ': cts)
171176 amrs = allMimeRender pctyps val
172177 lkup = fmap (\(a,b) -> (a, (fromStrict $ M.renderHeader a, b))) amrs
173178
174−
175179--------------------------------------------------------------------------
176180-- * Unrender
177181
@@ -199,14 +203,13 @@ instance (AllMimeRender ctyps a, IsNonEmpty ctyps) => AllCTRender ctyps a where
199203class Accept ctype => MimeUnrender ctype a where
200204 mimeUnrender :: Proxy ctype -> ByteString -> Either String a
201205
202−class (IsNonEmpty list) => AllCTUnrender (list :: [*]) a where
206+class AllCTUnrender (list :: [*]) a where
203207 handleCTypeH :: Proxy list
204208 -> ByteString -- Content-Type header
205209 -> ByteString -- Request body
206210 -> Maybe (Either String a)
207211
208−instance ( AllMimeUnrender ctyps a, IsNonEmpty ctyps
209− ) => AllCTUnrender ctyps a where
212+instance ( AllMimeUnrender ctyps a ) => AllCTUnrender ctyps a where
210213 handleCTypeH _ ctypeH body = M.mapContentMedia lkup (cs ctypeH)
211214 where lkup = allMimeUnrender (Proxy :: Proxy ctyps) body
212215
@@ -235,11 +238,12 @@ class (AllMime list) => AllMimeRender (list :: [*]) a where
235238 -> a -- value to serialize
236239 -> [(M.MediaType, ByteString)] -- content-types/response pairs
237240
238−instance ( MimeRender ctyp a ) => AllMimeRender '[ctyp] a where
241+instance OVERLAPPABLE_ ( MimeRender ctyp a ) => AllMimeRender '[ctyp] a where
239242 allMimeRender _ a = [(contentType pctyp, mimeRender pctyp a)]
240243 where pctyp = Proxy :: Proxy ctyp
241244
242−instance ( MimeRender ctyp a
245+instance OVERLAPPABLE_
246+ ( MimeRender ctyp a
243247 , AllMimeRender (ctyp' ': ctyps) a
244248 ) => AllMimeRender (ctyp ': ctyp' ': ctyps) a where
245249 allMimeRender _ a = (contentType pctyp, mimeRender pctyp a)
@@ -248,8 +252,17 @@ instance ( MimeRender ctyp a
248252 pctyps = Proxy :: Proxy (ctyp' ': ctyps)
249253
250254
251−instance AllMimeRender '[] a where
252− allMimeRender _ _ = []
255+-- Ideally we would like to declare a 'MimeRender a NoContent' instance, and
256+-- then this would be taken care of. However there is no more specific instance
257+-- between that and 'MimeRender JSON a', so we do this instead
258+instance OVERLAPPING_ ( Accept ctyp ) => AllMimeRender '[ctyp] NoContent where
259+ allMimeRender _ _ = [(contentType pctyp, "")]
260+ where pctyp = Proxy :: Proxy ctyp
261+
262+instance OVERLAPPING_
263+ ( AllMime (ctyp ': ctyp' ': ctyps)
264+ ) => AllMimeRender (ctyp ': ctyp' ': ctyps) NoContent where
265+ allMimeRender p _ = zip (allMime p) (repeat "")
253266
254267--------------------------------------------------------------------------
255268-- Check that all elements of list are instances of MimeUnrender
@@ -270,21 +283,19 @@ instance ( MimeUnrender ctyp a
270283 where pctyp = Proxy :: Proxy ctyp
271284 pctyps = Proxy :: Proxy ctyps
272285
273−type family IsNonEmpty (list :: [*]) :: Constraint where
274− IsNonEmpty (x ': xs) = ()
275−
276−
277286--------------------------------------------------------------------------
278287-- * MimeRender Instances
279288
280289-- | `encode`
281−instance ToJSON a => MimeRender JSON a where
290+instance OVERLAPPABLE_
291+ ToJSON a => MimeRender JSON a where
282292 mimeRender _ = encode
283293
284294-- | @encodeFormUrlEncoded . toFormUrlEncoded@
285295-- Note that the @mimeUnrender p (mimeRender p x) == Right x@ law only
286296-- holds if every element of x is non-null (i.e., not @("", "")@)
287−instance ToFormUrlEncoded a => MimeRender FormUrlEncoded a where
297+instance OVERLAPPABLE_
298+ ToFormUrlEncoded a => MimeRender FormUrlEncoded a where
288299 mimeRender _ = encodeFormUrlEncoded . toFormUrlEncoded
289300
290301-- | `TextL.encodeUtf8`
@@ -307,6 +318,10 @@ instance MimeRender OctetStream ByteString where
307318instance MimeRender OctetStream BS.ByteString where
308319 mimeRender _ = fromStrict
309320
321+-- | A type for responses without content-body.
322+data NoContent = NoContent
323+ deriving (Show, Eq, Read)
324+
310325
311326--------------------------------------------------------------------------
312327-- * MimeUnrender Instances
servant/src/Servant/API/Delete.hsdeleted−24
@@ -1,24 +0,0 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE KindSignatures #-}
4−{-# OPTIONS_HADDOCK not-home #-}
5−module Servant.API.Delete (Delete) where
6−
7−import Data.Typeable (Typeable)
8−
9−-- | Combinator for DELETE requests.
10−--
11−-- Example:
12−--
13−-- >>> -- DELETE /books/:isbn
14−-- >>> type MyApi = "books" :> Capture "isbn" Text :> Delete '[] ()
15−data Delete (contentTypes :: [*]) a
16− deriving Typeable
17−
18−
19−-- $setup
20−-- >>> import Servant.API
21−-- >>> import Data.Aeson
22−-- >>> import Data.Text
23−-- >>> data Book
24−-- >>> instance ToJSON Book where { toJSON = undefined }
servant/src/Servant/API/Get.hsdeleted−22
@@ -1,22 +0,0 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE KindSignatures #-}
4−{-# OPTIONS_HADDOCK not-home #-}
5−module Servant.API.Get (Get) where
6−
7−import Data.Typeable (Typeable)
8−
9−-- | Endpoint for simple GET requests. Serves the result as JSON.
10−--
11−-- Example:
12−--
13−-- >>> type MyApi = "books" :> Get '[JSON] [Book]
14−data Get (contentTypes :: [*]) a
15− deriving Typeable
16−
17−-- $setup
18−-- >>> import Servant.API
19−-- >>> import Data.Aeson
20−-- >>> import Data.Text
21−-- >>> data Book
22−-- >>> instance ToJSON Book where { toJSON = undefined }
servant/src/Servant/API/Patch.hsdeleted−29
@@ -1,29 +0,0 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE KindSignatures #-}
4−{-# OPTIONS_HADDOCK not-home #-}
5−module Servant.API.Patch (Patch) where
6−
7−import Data.Typeable (Typeable)
8−
9−-- | Endpoint for PATCH requests. The type variable represents the type of the
10−-- response body (not the request body, use 'Servant.API.ReqBody.ReqBody' for
11−-- that).
12−--
13−-- If the HTTP response is empty, only () is supported.
14−--
15−-- Example:
16−--
17−-- >>> -- PATCH /books
18−-- >>> -- with a JSON encoded Book as the request body
19−-- >>> -- returning the just-created Book
20−-- >>> type MyApi = "books" :> ReqBody '[JSON] Book :> Patch '[JSON] Book
21−data Patch (contentTypes :: [*]) a
22− deriving Typeable
23−
24−-- $setup
25−-- >>> import Servant.API
26−-- >>> import Data.Aeson
27−-- >>> import Data.Text
28−-- >>> data Book
29−-- >>> instance ToJSON Book where { toJSON = undefined }
servant/src/Servant/API/Post.hsdeleted−27
@@ -1,27 +0,0 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE KindSignatures #-}
4−{-# OPTIONS_HADDOCK not-home #-}
5−module Servant.API.Post (Post) where
6−
7−import Data.Typeable (Typeable)
8−
9−-- | Endpoint for POST requests. The type variable represents the type of the
10−-- response body (not the request body, use 'Servant.API.ReqBody.ReqBody' for
11−-- that).
12−--
13−-- Example:
14−--
15−-- >>> -- POST /books
16−-- >>> -- with a JSON encoded Book as the request body
17−-- >>> -- returning the just-created Book
18−-- >>> type MyApi = "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book
19−data Post (contentTypes :: [*]) a
20− deriving Typeable
21−
22−-- $setup
23−-- >>> import Servant.API
24−-- >>> import Data.Aeson
25−-- >>> import Data.Text
26−-- >>> data Book
27−-- >>> instance ToJSON Book where { toJSON = undefined }
servant/src/Servant/API/Put.hsdeleted−25
@@ -1,25 +0,0 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE KindSignatures #-}
4−{-# OPTIONS_HADDOCK not-home #-}
5−module Servant.API.Put (Put) where
6−
7−import Data.Typeable (Typeable)
8−
9−-- | Endpoint for PUT requests, usually used to update a ressource.
10−-- The type @a@ is the type of the response body that's returned.
11−--
12−-- Example:
13−--
14−-- >>> -- PUT /books/:isbn
15−-- >>> -- with a Book as request body, returning the updated Book
16−-- >>> type MyApi = "books" :> Capture "isbn" Text :> ReqBody '[JSON] Book :> Put '[JSON] Book
17−data Put (contentTypes :: [*]) a
18− deriving Typeable
19−
20−-- $setup
21−-- >>> import Servant.API
22−-- >>> import Data.Aeson
23−-- >>> import Data.Text
24−-- >>> data Book
25−-- >>> instance ToJSON Book where { toJSON = undefined }
servant/src/Servant/API/Verbs.hsnew file+169
@@ -0,0 +1,169 @@
1+{-# LANGUAGE DataKinds #-}
2+{-# LANGUAGE DeriveDataTypeable #-}
3+{-# LANGUAGE DeriveGeneric #-}
4+{-# LANGUAGE KindSignatures #-}
5+{-# LANGUAGE PolyKinds #-}
6+module Servant.API.Verbs
7+ ( module Servant.API.Verbs
8+ , StdMethod(GET, POST, HEAD, PUT, DELETE, TRACE, CONNECT, OPTIONS, PATCH)
9+ ) where
10+
11+import Data.Typeable (Typeable)
12+import Data.Proxy (Proxy)
13+import GHC.Generics (Generic)
14+import GHC.TypeLits (Nat)
15+import Network.HTTP.Types.Method (Method, StdMethod (..),
16+ methodDelete, methodGet, methodHead,
17+ methodPatch, methodPost, methodPut)
18+
19+-- | @Verb@ is a general type for representing HTTP verbs (a.k.a. methods). For
20+-- convenience, type synonyms for each verb with a 200 response code are
21+-- provided, but you are free to define your own:
22+--
23+-- >>> type Post204 contentTypes a = Verb 'POST 204 contentTypes a
24+data Verb (method :: k1) (statusCode :: Nat) (contentTypes :: [*]) a
25+ deriving (Typeable, Generic)
26+
27+-- * 200 responses
28+--
29+-- The 200 response is the workhorse of web servers, but also fairly generic.
30+-- When appropriate, you should prefer the more specific success combinators.
31+-- More information about the definitions of status codes can be found in
32+-- <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html RFC2615> and
33+-- <https://tools.ietf.org/html/rfc7231#section-6 RFC7231 Section 6>;
34+-- the relevant information is summarily presented here.
35+
36+-- | 'GET' with 200 status code.
37+type Get contentTypes a = Verb 'GET 200 contentTypes a
38+-- | 'POST' with 200 status code.
39+type Post contentTypes a = Verb 'POST 200 contentTypes a
40+-- | 'PUT' with 200 status code.
41+type Put contentTypes a = Verb 'PUT 200 contentTypes a
42+-- | 'DELETE' with 200 status code.
43+type Delete contentTypes a = Verb 'DELETE 200 contentTypes a
44+-- | 'PATCH' with 200 status code.
45+type Patch contentTypes a = Verb 'PATCH 200 contentTypes a
46+
47+-- * Other responses
48+
49+-- ** 201 Created
50+--
51+-- Indicates that a new resource has been created. The URI corresponding to the
52+-- resource should be given in the @Location@ header field.
53+--
54+-- If the resource cannot be created immediately, use 'PostAccepted'.
55+--
56+-- Consider using 'Servant.Utils.Links.safeLink' for the @Location@ header
57+-- field.
58+
59+-- | 'POST' with 201 status code.
60+--
61+type PostCreated contentTypes a = Verb 'POST 201 contentTypes a
62+
63+
64+-- ** 202 Accepted
65+--
66+-- Indicates that the request has been accepted for processing, but the
67+-- processing has not yet completed. The status of the processing should be
68+-- included, as well as either a link to a status monitoring endpoint or an
69+-- estimate of when the processing will be finished.
70+
71+-- | 'GET' with 202 status code.
72+type GetAccepted contentTypes a = Verb 'GET 202 contentTypes a
73+-- | 'POST' with 202 status code.
74+type PostAccepted contentTypes a = Verb 'POST 202 contentTypes a
75+-- | 'DELETE' with 202 status code.
76+type DeleteAccepted contentTypes a = Verb 'DELETE 202 contentTypes a
77+-- | 'PATCH' with 202 status code.
78+type PatchAccepted contentTypes a = Verb 'PATCH 202 contentTypes a
79+-- | 'PUT' with 202 status code.
80+type PutAccepted contentTypes a = Verb 'PUT 202 contentTypes a
81+
82+
83+-- ** 203 Non-Authoritative Information
84+--
85+-- Indicates that the request has been successfully processed, but the
86+-- information may come from a third-party.
87+
88+-- | 'GET' with 203 status code.
89+type GetNonAuthoritative contentTypes a = Verb 'GET 203 contentTypes a
90+-- | 'POST' with 203 status code.
91+type PostNonAuthoritative contentTypes a = Verb 'POST 203 contentTypes a
92+-- | 'DELETE' with 203 status code.
93+type DeleteNonAuthoritative contentTypes a = Verb 'DELETE 203 contentTypes a
94+-- | 'PATCH' with 203 status code.
95+type PatchNonAuthoritative contentTypes a = Verb 'PATCH 203 contentTypes a
96+-- | 'PUT' with 203 status code.
97+type PutNonAuthoritative contentTypes a = Verb 'PUT 203 contentTypes a
98+
99+
100+-- ** 204 No Content
101+--
102+-- Indicates that no response body is being returned. Handlers for these should
103+-- return 'NoContent', possibly with headers.
104+--
105+-- If the document view should be reset, use @205 Reset Content@.
106+
107+-- | 'GET' with 204 status code.
108+type GetNoContent contentTypes noContent = Verb 'GET 204 contentTypes noContent
109+-- | 'POST' with 204 status code.
110+type PostNoContent contentTypes noContent = Verb 'POST 204 contentTypes noContent
111+-- | 'DELETE' with 204 status code.
112+type DeleteNoContent contentTypes noContent = Verb 'DELETE 204 contentTypes noContent
113+-- | 'PATCH' with 204 status code.
114+type PatchNoContent contentTypes noContent = Verb 'PATCH 204 contentTypes noContent
115+-- | 'PUT' with 204 status code.
116+type PutNoContent contentTypes noContent = Verb 'PUT 204 contentTypes noContent
117+
118+
119+-- ** 205 Reset Content
120+--
121+-- Indicates that no response body is being returned. Handlers for these should
122+-- return 'NoContent', possibly with Headers.
123+--
124+-- If the document view should not be reset, use @204 No Content@.
125+
126+-- | 'GET' with 205 status code.
127+type GetResetContent contentTypes noContent = Verb 'GET 205 contentTypes noContent
128+-- | 'POST' with 205 status code.
129+type PostResetContent contentTypes noContent = Verb 'POST 205 contentTypes noContent
130+-- | 'DELETE' with 205 status code.
131+type DeleteResetContent contentTypes noContent = Verb 'DELETE 205 contentTypes noContent
132+-- | 'PATCH' with 205 status code.
133+type PatchResetContent contentTypes noContent = Verb 'PATCH 205 contentTypes noContent
134+-- | 'PUT' with 205 status code.
135+type PutResetContent contentTypes noContent = Verb 'PUT 205 contentTypes noContent
136+
137+
138+-- ** 206 Partial Content
139+--
140+-- Indicates that the server is delivering part of the resource due to a range
141+-- header in the request.
142+--
143+-- For more information, see <https://tools.ietf.org/html/rfc7233#section-4.1
144+-- RFC7233 Section 4.1>
145+
146+-- | 'GET' with 206 status code.
147+type GetPartialContent contentTypes noContent = Verb 'GET 206 contentTypes noContent
148+
149+
150+class ReflectMethod a where
151+ reflectMethod :: Proxy a -> Method
152+
153+instance ReflectMethod 'GET where
154+ reflectMethod _ = methodGet
155+
156+instance ReflectMethod 'POST where
157+ reflectMethod _ = methodPost
158+
159+instance ReflectMethod 'PUT where
160+ reflectMethod _ = methodPut
161+
162+instance ReflectMethod 'DELETE where
163+ reflectMethod _ = methodDelete
164+
165+instance ReflectMethod 'PATCH where
166+ reflectMethod _ = methodPatch
167+
168+instance ReflectMethod 'HEAD where
169+ reflectMethod _ = methodHead
servant/src/Servant/Utils/Links.hs+6−29
@@ -74,7 +74,7 @@
7474-- >>> safeLink api bad_link
7575-- ...
7676-- Could not deduce (Or
77−-- (IsElem' (Delete '[JSON] ()) (Get '[JSON] Int))
77+-- (IsElem' (Verb 'DELETE 200 '[JSON] ()) (Verb 'GET 200 '[JSON] Int))
7878-- (IsElem'
7979-- ("hello" :> Delete '[JSON] ())
8080-- ("bye" :> (QueryParam "name" String :> Delete '[JSON] ()))))
@@ -119,11 +119,7 @@ import Servant.API.Capture ( Capture )
119119import Servant.API.ReqBody ( ReqBody )
120120import Servant.API.QueryParam ( QueryParam, QueryParams, QueryFlag )
121121import Servant.API.Header ( Header )
122−import Servant.API.Get ( Get )
123−import Servant.API.Post ( Post )
124−import Servant.API.Put ( Put )
125−import Servant.API.Patch ( Patch )
126−import Servant.API.Delete ( Delete )
122+import Servant.API.Verbs ( Verb )
127123import Servant.API.Sub ( type (:>) )
128124import Servant.API.Raw ( Raw )
129125import Servant.API.Alternative ( type (:<|>) )
@@ -177,11 +173,8 @@ type family IsElem endpoint api :: Constraint where
177173 IsElem sa (QueryParam x y :> sb) = IsElem sa sb
178174 IsElem sa (QueryParams x y :> sb) = IsElem sa sb
179175 IsElem sa (QueryFlag x :> sb) = IsElem sa sb
180− IsElem (Get ct typ) (Get ct' typ) = IsSubList ct ct'
181− IsElem (Post ct typ) (Post ct' typ) = IsSubList ct ct'
182− IsElem (Put ct typ) (Put ct' typ) = IsSubList ct ct'
183− IsElem (Patch ct typ) (Patch ct' typ) = IsSubList ct ct'
184− IsElem (Delete ct typ) (Delete ct' typ) = IsSubList ct ct'
176+ IsElem (Verb m s ct typ) (Verb m s ct' typ)
177+ = IsSubList ct ct'
185178 IsElem e e = ()
186179 IsElem e a = IsElem' e a
187180
@@ -303,24 +296,8 @@ instance HasLink sub => HasLink (Header sym a :> sub) where
303296 toLink _ = toLink (Proxy :: Proxy sub)
304297
305298-- Verb (terminal) instances
306−instance HasLink (Get y r) where
307− type MkLink (Get y r) = URI
308− toLink _ = linkURI
309−
310−instance HasLink (Post y r) where
311− type MkLink (Post y r) = URI
312− toLink _ = linkURI
313−
314−instance HasLink (Put y r) where
315− type MkLink (Put y r) = URI
316− toLink _ = linkURI
317−
318−instance HasLink (Patch y r) where
319− type MkLink (Patch y r) = URI
320− toLink _ = linkURI
321−
322−instance HasLink (Delete y r) where
323− type MkLink (Delete y r) = URI
299+instance HasLink (Verb m s ct a) where
300+ type MkLink (Verb m s ct a) = URI
324301 toLink _ = linkURI
325302
326303instance HasLink Raw where