on master help sign in
Remove MatrixParam.
afc76b8Julian K. Arni
servant-client/src/Servant/Client.hs−128
@@ -477,134 +477,6 @@ instance (KnownSymbol sym, HasClient sublayout)
477
477
478 where paramname = cs $ symbolVal (Proxy :: Proxy sym)
478 where paramname = cs $ symbolVal (Proxy :: Proxy sym)
479
479
480−-- | If you use a 'MatrixParam' in one of your endpoints in your API,
481−-- the corresponding querying function will automatically take
482−-- an additional argument of the type specified by your 'MatrixParam',
483−-- enclosed in Maybe.
484−--
485−-- If you give Nothing, nothing will be added to the query string.
486−--
487−-- If you give a non-'Nothing' value, this function will take care
488−-- of inserting a textual representation of this value in the query string.
489−--
490−-- You can control how values for your type are turned into
491−-- text by specifying a 'ToHttpApiData' instance for your type.
492−--
493−-- Example:
494−--
495−-- > type MyApi = "books" :> MatrixParam "author" Text :> Get '[JSON] [Book]
496−-- >
497−-- > myApi :: Proxy MyApi
498−-- > myApi = Proxy
499−-- >
500−-- > getBooksBy :: Maybe Text -> ExceptT String IO [Book]
501−-- > getBooksBy = client myApi host
502−-- > where host = BaseUrl Http "localhost" 8080
503−-- > -- then you can just use "getBooksBy" to query that endpoint.
504−-- > -- 'getBooksBy Nothing' for all books
505−-- > -- 'getBooksBy (Just "Isaac Asimov")' to get all books by Isaac Asimov
506−instance (KnownSymbol sym, ToHttpApiData a, HasClient sublayout)
507− => HasClient (MatrixParam sym a :> sublayout) where
508−
509− type Client (MatrixParam sym a :> sublayout) =
510− Maybe a -> Client sublayout
511−
512− -- if mparam = Nothing, we don't add it to the query string
513− clientWithRoute Proxy req baseurl manager mparam =
514− clientWithRoute (Proxy :: Proxy sublayout)
515− (maybe req
516− (flip (appendToMatrixParams pname . Just) req)
517− mparamText
518− )
519− baseurl manager
520−
521− where pname = symbolVal (Proxy :: Proxy sym)
522− mparamText = fmap (cs . toQueryParam) mparam
523−
524−-- | If you use a 'MatrixParams' in one of your endpoints in your API,
525−-- the corresponding querying function will automatically take an
526−-- additional argument, a list of values of the type specified by your
527−-- 'MatrixParams'.
528−--
529−-- If you give an empty list, nothing will be added to the query string.
530−--
531−-- Otherwise, this function will take care of inserting a textual
532−-- representation of your values in the path segment string, under the
533−-- same matrix string parameter name.
534−--
535−-- You can control how values for your type are turned into text by
536−-- specifying a 'ToHttpApiData' instance for your type.
537−--
538−-- Example:
539−--
540−-- > type MyApi = "books" :> MatrixParams "authors" Text :> Get '[JSON] [Book]
541−-- >
542−-- > myApi :: Proxy MyApi
543−-- > myApi = Proxy
544−-- >
545−-- > getBooksBy :: [Text] -> ExceptT String IO [Book]
546−-- > getBooksBy = client myApi host
547−-- > where host = BaseUrl Http "localhost" 8080
548−-- > -- then you can just use "getBooksBy" to query that endpoint.
549−-- > -- 'getBooksBy []' for all books
550−-- > -- 'getBooksBy ["Isaac Asimov", "Robert A. Heinlein"]'
551−-- > -- to get all books by Asimov and Heinlein
552−instance (KnownSymbol sym, ToHttpApiData a, HasClient sublayout)
553− => HasClient (MatrixParams sym a :> sublayout) where
554−
555− type Client (MatrixParams sym a :> sublayout) =
556− [a] -> Client sublayout
557−
558− clientWithRoute Proxy req baseurl manager paramlist =
559− clientWithRoute (Proxy :: Proxy sublayout)
560− (foldl' (\ req' value -> maybe req' (flip (appendToMatrixParams pname) req' . Just . cs) value)
561− req
562− paramlist'
563− )
564− baseurl manager
565−
566− where pname = cs pname'
567− pname' = symbolVal (Proxy :: Proxy sym)
568− paramlist' = map (Just . toQueryParam) paramlist
569−
570−-- | If you use a 'MatrixFlag' in one of your endpoints in your API,
571−-- the corresponding querying function will automatically take an
572−-- additional 'Bool' argument.
573−--
574−-- If you give 'False', nothing will be added to the path segment.
575−--
576−-- Otherwise, this function will insert a value-less matrix parameter
577−-- under the name associated to your 'MatrixFlag'.
578−--
579−-- Example:
580−--
581−-- > type MyApi = "books" :> MatrixFlag "published" :> Get '[JSON] [Book]
582−-- >
583−-- >
584−-- > myApi :: Proxy MyApi
585−-- > myApi = Proxy
586−-- >
587−-- > getBooks :: Bool -> ExceptT String IO [Book]
588−-- > getBooks = client myApi host
589−-- > where host = BaseUrl Http "localhost" 8080
590−-- > -- then you can just use "getBooks" to query that endpoint.
591−-- > -- 'getBooksBy False' for all books
592−-- > -- 'getBooksBy True' to only get _already published_ books
593−instance (KnownSymbol sym, HasClient sublayout)
594− => HasClient (MatrixFlag sym :> sublayout) where
595−
596− type Client (MatrixFlag sym :> sublayout) =
597− Bool -> Client sublayout
598−
599− clientWithRoute Proxy req baseurl manager flag =
600− clientWithRoute (Proxy :: Proxy sublayout)
601− (if flag
602− then appendToMatrixParams paramname Nothing req
603− else req
604− )
605− baseurl manager
606−
607− where paramname = cs $ symbolVal (Proxy :: Proxy sym)
608
480
609-- | Pick a 'Method' and specify where the server you want to query is. You get
481-- | Pick a 'Method' and specify where the server you want to query is. You get
610-- back the full `Response`.
482-- back the full `Response`.
servant-client/src/Servant/Common/Req.hs−7
@@ -72,13 +72,6 @@ appendToPath :: String -> Req -> Req
72appendToPath p req =
72appendToPath p req =
73 req { reqPath = reqPath req ++ "/" ++ p }
73 req { reqPath = reqPath req ++ "/" ++ p }
74
74
75−appendToMatrixParams :: String
76− -> Maybe String
77− -> Req
78− -> Req
79−appendToMatrixParams pname pvalue req =
80− req { reqPath = reqPath req ++ ";" ++ pname ++ maybe "" ("=" ++) pvalue }
81−
82appendToQueryString :: Text -- ^ param name
75appendToQueryString :: Text -- ^ param name
83 -> Maybe Text -- ^ param value
76 -> Maybe Text -- ^ param value
84 -> Req
77 -> Req
servant-client/test/Servant/ClientSpec.hs+1−29
@@ -96,9 +96,6 @@ type Api =
96 :<|> "param" :> QueryParam "name" String :> Get '[FormUrlEncoded,JSON] Person
96 :<|> "param" :> QueryParam "name" String :> Get '[FormUrlEncoded,JSON] Person
97 :<|> "params" :> QueryParams "names" String :> Get '[JSON] [Person]
97 :<|> "params" :> QueryParams "names" String :> Get '[JSON] [Person]
98 :<|> "flag" :> QueryFlag "flag" :> Get '[JSON] Bool
98 :<|> "flag" :> QueryFlag "flag" :> Get '[JSON] Bool
99− :<|> "matrixparam" :> MatrixParam "name" String :> Get '[JSON] Person
100− :<|> "matrixparams" :> MatrixParams "name" String :> Get '[JSON] [Person]
101− :<|> "matrixflag" :> MatrixFlag "flag" :> Get '[JSON] Bool
102 :<|> "rawSuccess" :> Raw
99 :<|> "rawSuccess" :> Raw
103 :<|> "rawFailure" :> Raw
100 :<|> "rawFailure" :> Raw
104 :<|> "multiple" :>
101 :<|> "multiple" :>
@@ -124,12 +121,6 @@ server = serve api (
124 Nothing -> throwE $ ServantErr 400 "missing parameter" "" [])
121 Nothing -> throwE $ ServantErr 400 "missing parameter" "" [])
125 :<|> (\ names -> return (zipWith Person names [0..]))
122 :<|> (\ names -> return (zipWith Person names [0..]))
126 :<|> return
123 :<|> return
127− :<|> (\ name -> case name of
128− Just "alice" -> return alice
129− Just name -> throwE $ ServantErr 400 (name ++ " not found") "" []
130− Nothing -> throwE $ ServantErr 400 "missing parameter" "" [])
131− :<|> (\ names -> return (zipWith Person names [0..]))
132− :<|> return
133 :<|> (\ _request respond -> respond $ responseLBS ok200 [] "rawSuccess")
124 :<|> (\ _request respond -> respond $ responseLBS ok200 [] "rawSuccess")
134 :<|> (\ _request respond -> respond $ responseLBS badRequest400 [] "rawFailure")
125 :<|> (\ _request respond -> respond $ responseLBS badRequest400 [] "rawFailure")
135 :<|> (\ a b c d -> return (a, b, c, d))
126 :<|> (\ a b c d -> return (a, b, c, d))
@@ -198,26 +189,7 @@ sucessSpec = beforeAll (startWaiApp server) $ afterAll endWaiApp $ do
198 let getQueryFlag = getNth (Proxy :: Proxy 6) $ client api baseUrl manager
189 let getQueryFlag = getNth (Proxy :: Proxy 6) $ client api baseUrl manager
199 (left show <$> runExceptT (getQueryFlag flag)) `shouldReturn` Right flag
190 (left show <$> runExceptT (getQueryFlag flag)) `shouldReturn` Right flag
200
191
201− it "Servant.API.MatrixParam" $ \(_, baseUrl) -> do
202− let getMatrixParam = getNth (Proxy :: Proxy 7) $ client api baseUrl manager
203− left show <$> runExceptT (getMatrixParam (Just "alice")) `shouldReturn` Right alice
204− Left FailureResponse{..} <- runExceptT (getMatrixParam (Just "bob"))
205− responseStatus `shouldBe` Status 400 "bob not found"
206−
207− it "Servant.API.MatrixParam.MatrixParams" $ \(_, baseUrl) -> do
208− let getMatrixParams = getNth (Proxy :: Proxy 8) $ client api baseUrl manager
209− left show <$> runExceptT (getMatrixParams []) `shouldReturn` Right []
210− left show <$> runExceptT (getMatrixParams ["alice", "bob"])
211− `shouldReturn` Right [Person "alice" 0, Person "bob" 1]
212−
213− context "Servant.API.MatrixParam.MatrixFlag" $
214− forM_ [False, True] $ \ flag ->
215− it (show flag) $ \(_, baseUrl) -> do
216− let getMatrixFlag = getNth (Proxy :: Proxy 9) $ client api baseUrl manager
217− left show <$> runExceptT (getMatrixFlag flag) `shouldReturn` Right flag
218−
219− it "Servant.API.Raw on success" $ \(_, baseUrl) -> do
192+ it "Servant.API.Raw on success" $ do
220− let getRawSuccess = getNth (Proxy :: Proxy 10) $ client api baseUrl manager
221 res <- runExceptT (getRawSuccess methodGet)
193 res <- runExceptT (getRawSuccess methodGet)
222 case res of
194 case res of
223 Left e -> assertFailure $ show e
195 Left e -> assertFailure $ show e
servant-server/servant-server.cabal−1
@@ -37,7 +37,6 @@ library
37 Servant.Server
37 Servant.Server
38 Servant.Server.Internal
38 Servant.Server.Internal
39 Servant.Server.Internal.Enter
39 Servant.Server.Internal.Enter
40− Servant.Server.Internal.PathInfo
41 Servant.Server.Internal.Router
40 Servant.Server.Internal.Router
42 Servant.Server.Internal.RoutingApplication
41 Servant.Server.Internal.RoutingApplication
43 Servant.Server.Internal.ServantErr
42 Servant.Server.Internal.ServantErr
servant-server/src/Servant/Server/Internal.hs+8−124
@@ -14,7 +14,6 @@
14
14
15module Servant.Server.Internal
15module Servant.Server.Internal
16 ( module Servant.Server.Internal
16 ( module Servant.Server.Internal
17− , module Servant.Server.Internal.PathInfo
18 , module Servant.Server.Internal.Router
17 , module Servant.Server.Internal.Router
19 , module Servant.Server.Internal.RoutingApplication
18 , module Servant.Server.Internal.RoutingApplication
20 , module Servant.Server.Internal.ServantErr
19 , module Servant.Server.Internal.ServantErr
@@ -31,8 +30,6 @@ import Data.Maybe (mapMaybe, fromMaybe)
31import Data.String (fromString)
30import Data.String (fromString)
32import Data.String.Conversions (cs, (<>), ConvertibleStrings)
31import Data.String.Conversions (cs, (<>), ConvertibleStrings)
33import Data.Text (Text)
32import Data.Text (Text)
34−import qualified Data.Text as T
35−import Data.Text.Encoding (encodeUtf8)
36import Data.Typeable
33import Data.Typeable
37import GHC.TypeLits (KnownSymbol, symbolVal)
34import GHC.TypeLits (KnownSymbol, symbolVal)
38import Network.HTTP.Types hiding (Header, ResponseHeaders)
35import Network.HTTP.Types hiding (Header, ResponseHeaders)
@@ -41,11 +38,10 @@ import Network.Wai (Application, lazyRequestBody,
41 rawQueryString, requestHeaders,
38 rawQueryString, requestHeaders,
42 requestMethod, responseLBS, remoteHost,
39 requestMethod, responseLBS, remoteHost,
43 isSecure, vault, httpVersion, Response,
40 isSecure, vault, httpVersion, Response,
44− Request)
41+ Request, pathInfo)
45import Servant.API ((:<|>) (..), (:>), Capture,
42import Servant.API ((:<|>) (..), (:>), Capture,
46 Delete, Get, Header,
43 Delete, Get, Header,
47− IsSecure(..), MatrixFlag, MatrixParam,
48− MatrixParams, Patch, Post, Put,
44+ IsSecure(..), Patch, Post, Put,
49 QueryFlag, QueryParam, QueryParams,
45 QueryFlag, QueryParam, QueryParams,
50 Raw, RemoteHost, ReqBody, Vault)
46 Raw, RemoteHost, ReqBody, Vault)
51import Servant.API.ContentTypes (AcceptHeader (..),
47import Servant.API.ContentTypes (AcceptHeader (..),
@@ -54,7 +50,6 @@ import Servant.API.ContentTypes (AcceptHeader (..),
54import Servant.API.ResponseHeaders (Headers, getResponse, GetHeaders,
50import Servant.API.ResponseHeaders (Headers, getResponse, GetHeaders,
55 getHeaders)
51 getHeaders)
56
52
57−import Servant.Server.Internal.PathInfo
58import Servant.Server.Internal.Router
53import Servant.Server.Internal.Router
59import Servant.Server.Internal.RoutingApplication
54import Servant.Server.Internal.RoutingApplication
60import Servant.Server.Internal.ServantErr
55import Servant.Server.Internal.ServantErr
@@ -548,123 +543,6 @@ instance (KnownSymbol sym, HasServer sublayout)
548 examine v | v == "true" || v == "1" || v == "" = True
543 examine v | v == "true" || v == "1" || v == "" = True
549 | otherwise = False
544 | otherwise = False
550
545
551−parseMatrixText :: B.ByteString -> QueryText
552−parseMatrixText = parseQueryText
553−
554−-- | If you use @'MatrixParam' "author" Text@ in one of the endpoints for your API,
555−-- this automatically requires your server-side handler to be a function
556−-- that takes an argument of type @'Maybe' 'Text'@.
557−--
558−-- This lets servant worry about looking it up in the query string
559−-- and turning it into a value of the type you specify, enclosed
560−-- in 'Maybe', because it may not be there and servant would then
561−-- hand you 'Nothing'.
562−--
563−-- You can control how it'll be converted from 'Text' to your type
564−-- by simply providing an instance of 'FromHttpApiData' for your type.
565−--
566−-- Example:
567−--
568−-- > type MyApi = "books" :> MatrixParam "author" Text :> Get [Book]
569−-- >
570−-- > server :: Server MyApi
571−-- > server = getBooksBy
572−-- > where getBooksBy :: Maybe Text -> ExceptT ServantErr IO [Book]
573−-- > getBooksBy Nothing = ...return all books...
574−-- > getBooksBy (Just author) = ...return books by the given author...
575−instance (KnownSymbol sym, FromHttpApiData a, HasServer sublayout)
576− => HasServer (MatrixParam sym a :> sublayout) where
577−
578− type ServerT (MatrixParam sym a :> sublayout) m =
579− Maybe a -> ServerT sublayout m
580−
581− route Proxy subserver = WithRequest $ \ request ->
582− case parsePathInfo request of
583− (first : _)
584− -> do let querytext = parseMatrixText . encodeUtf8 $ T.tail first
585− param = case lookup paramname querytext of
586− Nothing -> Nothing -- param absent from the query string
587− Just Nothing -> Nothing -- param present with no value -> Nothing
588− Just (Just v) -> parseQueryParamMaybe v -- if present, we try to convert to
589− -- the right type
590− route (Proxy :: Proxy sublayout) (feedTo subserver param)
591− _ -> route (Proxy :: Proxy sublayout) (feedTo subserver Nothing)
592−
593− where paramname = cs $ symbolVal (Proxy :: Proxy sym)
594−
595−-- | If you use @'MatrixParams' "authors" Text@ in one of the endpoints for your API,
596−-- this automatically requires your server-side handler to be a function
597−-- that takes an argument of type @['Text']@.
598−--
599−-- This lets servant worry about looking up 0 or more values in the query string
600−-- associated to @authors@ and turning each of them into a value of
601−-- the type you specify.
602−--
603−-- You can control how the individual values are converted from 'Text' to your type
604−-- by simply providing an instance of 'FromHttpApiData' for your type.
605−--
606−-- Example:
607−--
608−-- > type MyApi = "books" :> MatrixParams "authors" Text :> Get [Book]
609−-- >
610−-- > server :: Server MyApi
611−-- > server = getBooksBy
612−-- > where getBooksBy :: [Text] -> ExceptT ServantErr IO [Book]
613−-- > getBooksBy authors = ...return all books by these authors...
614−instance (KnownSymbol sym, FromHttpApiData a, HasServer sublayout)
615− => HasServer (MatrixParams sym a :> sublayout) where
616−
617− type ServerT (MatrixParams sym a :> sublayout) m =
618− [a] -> ServerT sublayout m
619−
620− route Proxy subserver = WithRequest $ \ request ->
621− case parsePathInfo request of
622− (first : _)
623− -> do let matrixtext = parseMatrixText . encodeUtf8 $ T.tail first
624− -- if sym is "foo", we look for matrix parameters
625− -- named "foo" or "foo[]" and call parseQueryParam on the
626− -- corresponding values
627− parameters = filter looksLikeParam matrixtext
628− values = mapMaybe (convert . snd) parameters
629− route (Proxy :: Proxy sublayout) (feedTo subserver values)
630− _ -> route (Proxy :: Proxy sublayout) (feedTo subserver [])
631− where paramname = cs $ symbolVal (Proxy :: Proxy sym)
632− looksLikeParam (name, _) = name == paramname || name == (paramname <> "[]")
633− convert Nothing = Nothing
634− convert (Just v) = parseQueryParamMaybe v
635−
636−-- | If you use @'MatrixFlag' "published"@ in one of the endpoints for your API,
637−-- this automatically requires your server-side handler to be a function
638−-- that takes an argument of type 'Bool'.
639−--
640−-- Example:
641−--
642−-- > type MyApi = "books" :> MatrixFlag "published" :> Get [Book]
643−-- >
644−-- > server :: Server MyApi
645−-- > server = getBooks
646−-- > where getBooks :: Bool -> ExceptT ServantErr IO [Book]
647−-- > getBooks onlyPublished = ...return all books, or only the ones that are already published, depending on the argument...
648−instance (KnownSymbol sym, HasServer sublayout)
649− => HasServer (MatrixFlag sym :> sublayout) where
650−
651− type ServerT (MatrixFlag sym :> sublayout) m =
652− Bool -> ServerT sublayout m
653−
654− route Proxy subserver = WithRequest $ \ request ->
655− case parsePathInfo request of
656− (first : _)
657− -> do let matrixtext = parseMatrixText . encodeUtf8 $ T.tail first
658− param = case lookup paramname matrixtext of
659− Just Nothing -> True -- param is there, with no value
660− Just (Just v) -> examine v -- param with a value
661− Nothing -> False -- param not in the query string
662− route (Proxy :: Proxy sublayout) (feedTo subserver param)
663− _ -> route (Proxy :: Proxy sublayout) (feedTo subserver False)
664− where paramname = cs $ symbolVal (Proxy :: Proxy sym)
665− examine v | v == "true" || v == "1" || v == "" = True
666− | otherwise = False
667−
668-- | Just pass the request to the underlying application and serve its response.
546-- | Just pass the request to the underlying application and serve its response.
669--
547--
670-- Example:
548-- Example:
@@ -762,5 +640,11 @@ instance HasServer api => HasServer (HttpVersion :> api) where
762 route Proxy subserver = WithRequest $ \req ->
640 route Proxy subserver = WithRequest $ \req ->
763 route (Proxy :: Proxy api) (feedTo subserver $ httpVersion req)
641 route (Proxy :: Proxy api) (feedTo subserver $ httpVersion req)
764
642
643+pathIsEmpty :: Request -> Bool
644+pathIsEmpty = go . pathInfo
645+ where go [] = True
646+ go [""] = True
647+ go _ = False
648+
765ct_wildcard :: B.ByteString
649ct_wildcard :: B.ByteString
766ct_wildcard = "*" <> "/" <> "*" -- Because CPP
650ct_wildcard = "*" <> "/" <> "*" -- Because CPP
servant-server/src/Servant/Server/Internal/PathInfo.hsdeleted−38
@@ -1,38 +0,0 @@
1−{-# LANGUAGE OverloadedStrings #-}
2−module Servant.Server.Internal.PathInfo where
3−
4−import Data.List (unfoldr)
5−import Data.Text (Text)
6−import qualified Data.Text as T
7−import Network.Wai (Request, pathInfo)
8−
9−-- | Like `null . pathInfo`, but works with redundant trailing slashes.
10−pathIsEmpty :: Request -> Bool
11−pathIsEmpty = f . processedPathInfo
12− where
13− f [] = True
14− f [""] = True
15− f _ = False
16−
17−
18−splitMatrixParameters :: Text -> (Text, Text)
19−splitMatrixParameters = T.break (== ';')
20−
21−parsePathInfo :: Request -> [Text]
22−parsePathInfo = filter (/= "") . mergePairs . map splitMatrixParameters . pathInfo
23− where mergePairs = concat . unfoldr pairToList
24− pairToList [] = Nothing
25− pairToList ((a, b):xs) = Just ([a, b], xs)
26−
27−-- | Returns a processed pathInfo from the request.
28−--
29−-- In order to handle matrix parameters in the request correctly, the raw pathInfo needs to be
30−-- processed, so routing works as intended. Therefor this function should be used to access
31−-- the pathInfo for routing purposes.
32−processedPathInfo :: Request -> [Text]
33−processedPathInfo r =
34− case pinfo of
35− (x:xs) | T.head x == ';' -> xs
36− _ -> pinfo
37− where pinfo = parsePathInfo r
38−
servant-server/src/Servant/Server/Internal/Router.hs+2−3
@@ -7,7 +7,6 @@ import qualified Data.Map as M
7import Data.Monoid ((<>))
7import Data.Monoid ((<>))
8import Data.Text (Text)
8import Data.Text (Text)
9import Network.Wai (Request, Response, pathInfo)
9import Network.Wai (Request, Response, pathInfo)
10−import Servant.Server.Internal.PathInfo
11import Servant.Server.Internal.RoutingApplication
10import Servant.Server.Internal.RoutingApplication
12
11
13type Router = Router' RoutingApplication
12type Router = Router' RoutingApplication
@@ -59,14 +58,14 @@ runRouter :: Router -> RoutingApplication
59runRouter (WithRequest router) request respond =
58runRouter (WithRequest router) request respond =
60 runRouter (router request) request respond
59 runRouter (router request) request respond
61runRouter (StaticRouter table) request respond =
60runRouter (StaticRouter table) request respond =
62− case processedPathInfo request of
61+ case pathInfo request of
63 first : rest
62 first : rest
64 | Just router <- M.lookup first table
63 | Just router <- M.lookup first table
65 -> let request' = request { pathInfo = rest }
64 -> let request' = request { pathInfo = rest }
66 in runRouter router request' respond
65 in runRouter router request' respond
67 _ -> respond $ failWith NotFound
66 _ -> respond $ failWith NotFound
68runRouter (DynamicRouter fun) request respond =
67runRouter (DynamicRouter fun) request respond =
69− case processedPathInfo request of
68+ case pathInfo request of
70 first : rest
69 first : rest
71 -> let request' = request { pathInfo = rest }
70 -> let request' = request { pathInfo = rest }
72 in runRouter (fun first) request' respond
71 in runRouter (fun first) request' respond
servant-server/test/Servant/ServerSpec.hs+7−91
@@ -38,13 +38,13 @@ import Test.Hspec (Spec, describe, it, shouldBe)
38import Test.Hspec.Wai (get, liftIO, matchHeaders,
38import Test.Hspec.Wai (get, liftIO, matchHeaders,
39 matchStatus, post, request,
39 matchStatus, post, request,
40 shouldRespondWith, with, (<:>))
40 shouldRespondWith, with, (<:>))
41−import Servant.API ((:<|>) (..), (:>),
41+import Servant.API ((:<|>) (..), (:>), Capture, Delete,
42− addHeader, Capture,
43− Delete, Get, Header (..), Headers,
42+ Get, Header (..), Headers,
44− HttpVersion, IsSecure(..), JSON, MatrixFlag,
43+ HttpVersion, IsSecure (..), JSON,
45− MatrixParam, MatrixParams, Patch, PlainText,
44+ Patch, PlainText, Post, Put,
46− Post, Put, RemoteHost, QueryFlag, QueryParam,
45+ QueryFlag, QueryParam, QueryParams,
47− QueryParams, Raw, ReqBody)
46+ Raw, RemoteHost, ReqBody,
47+ addHeader)
48import Servant.Server (Server, serve, ServantErr(..), err404)
48import Servant.Server (Server, serve, ServantErr(..), err404)
49import Servant.Server.Internal.Router
49import Servant.Server.Internal.Router
50 (tweakResponse, runRouter,
50 (tweakResponse, runRouter,
@@ -95,7 +95,6 @@ spec = do
95 putSpec
95 putSpec
96 patchSpec
96 patchSpec
97 queryParamSpec
97 queryParamSpec
98− matrixParamSpec
99 headerSpec
98 headerSpec
100 rawSpec
99 rawSpec
101 unionSpec
100 unionSpec
@@ -275,89 +274,6 @@ queryParamSpec = do
275 name = "Alice"
274 name = "Alice"
276 }
275 }
277
276
278−type MatrixParamApi = "a" :> MatrixParam "name" String :> Get '[JSON] Person
279− :<|> "b" :> MatrixParams "names" String :> "bsub" :> MatrixParams "names" String :> Get '[JSON] Person
280− :<|> "c" :> MatrixFlag "capitalize" :> Get '[JSON] Person
281− :<|> "d" :> Capture "foo" Integer :> MatrixParam "name" String :> MatrixFlag "capitalize" :> "dsub" :> Get '[JSON] Person
282−
283−matrixParamApi :: Proxy MatrixParamApi
284−matrixParamApi = Proxy
285−
286−mpServer :: Server MatrixParamApi
287−mpServer = matrixParamServer :<|> mpNames :<|> mpCapitalize alice :<|> mpComplex
288− where mpNames (_:name2:_) _ = return alice { name = name2 }
289− mpNames _ _ = return alice
290−
291− mpCapitalize p False = return p
292− mpCapitalize p True = return p { name = map toUpper (name p) }
293−
294− matrixParamServer (Just name) = return alice{name = name}
295− matrixParamServer Nothing = return alice
296−
297− mpAge age p = return p { age = age }
298− mpComplex capture name cap = matrixParamServer name >>= flip mpCapitalize cap >>= mpAge capture
299−
300−matrixParamSpec :: Spec
301−matrixParamSpec = do
302− describe "Servant.API.MatrixParam" $ do
303− it "allows to retrieve simple matrix parameters" $
304− (flip runSession) (serve matrixParamApi mpServer) $ do
305− response1 <- Network.Wai.Test.request defaultRequest{
306− pathInfo = ["a;name=bob"]
307− }
308− liftIO $ do
309− decode' (simpleBody response1) `shouldBe` Just alice{
310− name = "bob"
311− }
312−
313− it "allows to retrieve lists in matrix parameters" $
314− (flip runSession) (serve matrixParamApi mpServer) $ do
315− response2 <- Network.Wai.Test.request defaultRequest{
316− pathInfo = ["b;names=bob;names=john", "bsub;names=anna;names=sarah"]
317− }
318− liftIO $
319− decode' (simpleBody response2) `shouldBe` Just alice{
320− name = "john"
321− }
322−
323− it "allows to retrieve value-less matrix parameters" $
324− (flip runSession) (serve matrixParamApi mpServer) $ do
325− response3 <- Network.Wai.Test.request defaultRequest{
326− pathInfo = ["c;capitalize"]
327− }
328− liftIO $
329− decode' (simpleBody response3) `shouldBe` Just alice{
330− name = "ALICE"
331− }
332−
333− response3' <- Network.Wai.Test.request defaultRequest{
334− pathInfo = ["c;capitalize="]
335− }
336− liftIO $
337− decode' (simpleBody response3') `shouldBe` Just alice{
338− name = "ALICE"
339− }
340−
341− it "allows to retrieve matrix parameters on captured segments" $
342− (flip runSession) (serve matrixParamApi mpServer) $ do
343− response4 <- Network.Wai.Test.request defaultRequest{
344− pathInfo = ["d", "12;name=stephen;capitalize", "dsub"]
345− }
346− liftIO $
347− decode' (simpleBody response4) `shouldBe` Just alice{
348− name = "STEPHEN",
349− age = 12
350− }
351−
352− response4' <- Network.Wai.Test.request defaultRequest{
353− pathInfo = ["d;ignored=1", "5", "dsub"]
354− }
355− liftIO $
356− decode' (simpleBody response4') `shouldBe` Just alice{
357− name = "Alice",
358− age = 5
359− }
360−
361type PostApi =
277type PostApi =
362 ReqBody '[JSON] Person :> Post '[JSON] Integer
278 ReqBody '[JSON] Person :> Post '[JSON] Integer
363 :<|> "bla" :> ReqBody '[JSON] Person :> Post '[JSON] Integer
279 :<|> "bla" :> ReqBody '[JSON] Person :> Post '[JSON] Integer
servant/servant.cabal−1
@@ -37,7 +37,6 @@ library
37 Servant.API.Post
37 Servant.API.Post
38 Servant.API.Put
38 Servant.API.Put
39 Servant.API.QueryParam
39 Servant.API.QueryParam
40− Servant.API.MatrixParam
41 Servant.API.Raw
40 Servant.API.Raw
42 Servant.API.RemoteHost
41 Servant.API.RemoteHost
43 Servant.API.ReqBody
42 Servant.API.ReqBody
servant/src/Servant/API.hs−4
@@ -17,8 +17,6 @@ module Servant.API (
17 -- | Retrieving parameters from the query string of the 'URI': @'QueryParam'@
17 -- | Retrieving parameters from the query string of the 'URI': @'QueryParam'@
18 module Servant.API.ReqBody,
18 module Servant.API.ReqBody,
19 -- | Accessing the request body as a JSON-encoded type: @'ReqBody'@
19 -- | Accessing the request body as a JSON-encoded type: @'ReqBody'@
20− module Servant.API.MatrixParam,
21− -- | Retrieving matrix parameters from the 'URI' segment: @'MatrixParam'@
22 module Servant.API.RemoteHost,
20 module Servant.API.RemoteHost,
23 -- | Retrieving the IP of the client
21 -- | Retrieving the IP of the client
24 module Servant.API.IsSecure,
22 module Servant.API.IsSecure,
@@ -71,8 +69,6 @@ import Servant.API.Get (Get)
71import Servant.API.Header (Header (..))
69import Servant.API.Header (Header (..))
72import Servant.API.HttpVersion (HttpVersion (..))
70import Servant.API.HttpVersion (HttpVersion (..))
73import Servant.API.IsSecure (IsSecure (..))
71import Servant.API.IsSecure (IsSecure (..))
74−import Servant.API.MatrixParam (MatrixFlag, MatrixParam,
75− MatrixParams)
76import Servant.API.Patch (Patch)
72import Servant.API.Patch (Patch)
77import Servant.API.Post (Post)
73import Servant.API.Post (Post)
78import Servant.API.Put (Put)
74import Servant.API.Put (Put)
servant/src/Servant/API/MatrixParam.hsdeleted−51
@@ -1,51 +0,0 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE PolyKinds #-}
4−{-# OPTIONS_HADDOCK not-home #-}
5−module Servant.API.MatrixParam (MatrixFlag, MatrixParam, MatrixParams) where
6−
7−import Data.Typeable (Typeable)
8−import GHC.TypeLits (Symbol)
9−-- | Lookup the value associated to the @sym@ matrix string parameter
10−-- and try to extract it as a value of type @a@.
11−--
12−-- Example:
13−--
14−-- >>> -- /books;author=<author name>
15−-- >>> type MyApi = "books" :> MatrixParam "author" Text :> Get '[JSON] [Book]
16−data MatrixParam (sym :: Symbol) a
17− deriving (Typeable)
18−
19−-- | Lookup the values associated to the @sym@ matrix string parameter
20−-- and try to extract it as a value of type @[a]@. This is typically
21−-- meant to support matrix string parameters of the form
22−-- @param[]=val1;param[]=val2@ and so on. Note that servant doesn't actually
23−-- require the @[]@s and will fetch the values just fine with
24−-- @param=val1;param=val2@, too.
25−--
26−-- Example:
27−--
28−-- >>> -- /books;authors[]=<author1>;authors[]=<author2>;...
29−-- >>> type MyApi = "books" :> MatrixParams "authors" Text :> Get '[JSON] [Book]
30−data MatrixParams (sym :: Symbol) a
31− deriving (Typeable)
32−
33−-- | Lookup a potentially value-less matrix string parameter
34−-- with boolean semantics. If the param @sym@ is there without any value,
35−-- or if it's there with value "true" or "1", it's interpreted as 'True'.
36−-- Otherwise, it's interpreted as 'False'.
37−--
38−-- Example:
39−--
40−-- >>> -- /books;published
41−-- >>> type MyApi = "books" :> MatrixFlag "published" :> Get '[JSON] [Book]
42−data MatrixFlag (sym :: Symbol)
43− deriving (Typeable)
44−
45−
46−-- $setup
47−-- >>> import Servant.API
48−-- >>> import Data.Aeson
49−-- >>> import Data.Text
50−-- >>> data Book
51−-- >>> instance ToJSON Book where { toJSON = undefined }
servant/src/Servant/Utils/Links.hs+1−50
@@ -117,7 +117,6 @@ import Web.HttpApiData
117import Servant.API.Capture ( Capture )
117import Servant.API.Capture ( Capture )
118import Servant.API.ReqBody ( ReqBody )
118import Servant.API.ReqBody ( ReqBody )
119import Servant.API.QueryParam ( QueryParam, QueryParams, QueryFlag )
119import Servant.API.QueryParam ( QueryParam, QueryParams, QueryFlag )
120−import Servant.API.MatrixParam ( MatrixParam, MatrixParams, MatrixFlag )
121import Servant.API.Header ( Header )
120import Servant.API.Header ( Header )
122import Servant.API.Get ( Get )
121import Servant.API.Get ( Get )
123import Servant.API.Post ( Post )
122import Servant.API.Post ( Post )
@@ -173,9 +172,6 @@ type family IsElem endpoint api :: Constraint where
173 IsElem sa (QueryParam x y :> sb) = IsElem sa sb
172 IsElem sa (QueryParam x y :> sb) = IsElem sa sb
174 IsElem sa (QueryParams x y :> sb) = IsElem sa sb
173 IsElem sa (QueryParams x y :> sb) = IsElem sa sb
175 IsElem sa (QueryFlag x :> sb) = IsElem sa sb
174 IsElem sa (QueryFlag x :> sb) = IsElem sa sb
176− IsElem sa (MatrixParam x y :> sb) = IsElem sa sb
177− IsElem sa (MatrixParams x y :> sb) = IsElem sa sb
178− IsElem sa (MatrixFlag x :> sb) = IsElem sa sb
179 IsElem (Get ct typ) (Get ct' typ) = IsSubList ct ct'
175 IsElem (Get ct typ) (Get ct' typ) = IsSubList ct ct'
180 IsElem (Post ct typ) (Post ct' typ) = IsSubList ct ct'
176 IsElem (Post ct typ) (Post ct' typ) = IsSubList ct ct'
181 IsElem (Put ct typ) (Put ct' typ) = IsSubList ct ct'
177 IsElem (Put ct typ) (Put ct' typ) = IsSubList ct ct'
@@ -192,10 +188,9 @@ type family IsSubList a b :: Constraint where
192 IsSubList (x ': xs) y = IsSubList '[x] y `And` IsSubList xs y
188 IsSubList (x ': xs) y = IsSubList '[x] y `And` IsSubList xs y
193
189
194-- Phantom types for Param
190-- Phantom types for Param
195−data Matrix
196data Query
191data Query
197
192
198−-- | Query/Matrix param
193+-- | Query param
199data Param a
194data Param a
200 = SingleParam String Text
195 = SingleParam String Text
201 | ArrayElemParam String Text
196 | ArrayElemParam String Text
@@ -209,21 +204,6 @@ addQueryParam :: Param Query -> Link -> Link
209addQueryParam qp l =
204addQueryParam qp l =
210 l { _queryParams = _queryParams l <> [qp] }
205 l { _queryParams = _queryParams l <> [qp] }
211
206
212−-- Not particularly efficient for many updates. Something to optimise if it's
213−-- a problem.
214−addMatrixParam :: Param Matrix -> Link -> Link
215−addMatrixParam param l = l { _segments = f (_segments l) }
216− where
217− f [] = []
218− f xs = init xs <> [g (last xs)]
219− -- Modify the segment at the "top" of the stack
220− g :: String -> String
221− g seg =
222− case param of
223− SingleParam k v -> seg <> ";" <> k <> "=" <> escape (unpack v)
224− ArrayElemParam k v -> seg <> ";" <> k <> "[]=" <> escape (unpack v)
225− FlagParam k -> seg <> ";" <> k
226−
227linkURI :: Link -> URI
207linkURI :: Link -> URI
228linkURI (Link segments q_params) =
208linkURI (Link segments q_params) =
229 URI mempty -- No scheme (relative)
209 URI mempty -- No scheme (relative)
@@ -300,35 +280,6 @@ instance (KnownSymbol sym, HasLink sub)
300 where
280 where
301 k = symbolVal (Proxy :: Proxy sym)
281 k = symbolVal (Proxy :: Proxy sym)
302
282
303−-- MatrixParam instances
304−instance (KnownSymbol sym, ToHttpApiData v, HasLink sub)
305− => HasLink (MatrixParam sym v :> sub) where
306− type MkLink (MatrixParam sym v :> sub) = Maybe v -> MkLink sub
307− toLink _ l mv =
308− toLink (Proxy :: Proxy sub) $
309− maybe id (addMatrixParam . SingleParam k . toQueryParam) mv l
310− where
311− k = symbolVal (Proxy :: Proxy sym)
312−
313−instance (KnownSymbol sym, ToHttpApiData v, HasLink sub)
314− => HasLink (MatrixParams sym v :> sub) where
315− type MkLink (MatrixParams sym v :> sub) = [v] -> MkLink sub
316− toLink _ l =
317− toLink (Proxy :: Proxy sub) .
318− foldl' (\l' v -> addMatrixParam (ArrayElemParam k (toQueryParam v)) l') l
319− where
320− k = symbolVal (Proxy :: Proxy sym)
321−
322−instance (KnownSymbol sym, HasLink sub)
323− => HasLink (MatrixFlag sym :> sub) where
324− type MkLink (MatrixFlag sym :> sub) = Bool -> MkLink sub
325− toLink _ l False =
326− toLink (Proxy :: Proxy sub) l
327− toLink _ l True =
328− toLink (Proxy :: Proxy sub) $ addMatrixParam (FlagParam k) l
329− where
330− k = symbolVal (Proxy :: Proxy sym)
331−
332-- Misc instances
283-- Misc instances
333instance HasLink sub => HasLink (ReqBody ct a :> sub) where
284instance HasLink sub => HasLink (ReqBody ct a :> sub) where
334 type MkLink (ReqBody ct a :> sub) = MkLink sub
285 type MkLink (ReqBody ct a :> sub) = MkLink sub
servant/test/Servant/Utils/LinksSpec.hs+3−20
@@ -11,14 +11,10 @@ import Data.Proxy ( Proxy(..) )
11import Servant.API
11import Servant.API
12
12
13type TestApi =
13type TestApi =
14− -- Capture and query/matrix params
14+ -- Capture and query params
15 "hello" :> Capture "name" String :> QueryParam "capital" Bool :> Delete '[JSON] ()
15 "hello" :> Capture "name" String :> QueryParam "capital" Bool :> Delete '[JSON] ()
16
16
17− :<|> "parent" :> MatrixParams "name" String :> "child"
18− :> MatrixParam "gender" String :> Get '[JSON] String
19−
20 -- Flags
17 -- Flags
21− :<|> "ducks" :> MatrixFlag "yellow" :> MatrixFlag "loud" :> Delete '[JSON] ()
22 :<|> "balls" :> QueryFlag "bouncy" :> QueryFlag "fast" :> Delete '[JSON] ()
18 :<|> "balls" :> QueryFlag "bouncy" :> QueryFlag "fast" :> Delete '[JSON] ()
23
19
24 -- All of the verbs
20 -- All of the verbs
@@ -34,7 +30,6 @@ type TestLink3 = "parent" :> "child" :> Get '[JSON] String
34
30
35type BadTestLink = "hallo" :> "hi" :> Get '[JSON] Bool
31type BadTestLink = "hallo" :> "hi" :> Get '[JSON] Bool
36type BadTestLink2 = "greet" :> Get '[PlainText] Bool
32type BadTestLink2 = "greet" :> Get '[PlainText] Bool
37−type BadTestLink3 = "parent" :> "child" :> MatrixFlag "male" :> Get '[JSON] String
38
33
39type BadTestLink' = "hello" :> "hi" :> Get '[OctetStream] Bool
34type BadTestLink' = "hello" :> "hi" :> Get '[OctetStream] Bool
40type BadTestLink'2 = "greet" :> Get '[OctetStream] Bool
35type BadTestLink'2 = "greet" :> Get '[OctetStream] Bool
@@ -54,7 +49,7 @@ shouldBeURI link expected =
54
49
55spec :: Spec
50spec :: Spec
56spec = describe "Servant.Utils.Links" $ do
51spec = describe "Servant.Utils.Links" $ do
57− it "Generates correct links for capture query and matrix params" $ do
52+ it "Generates correct links for capture query params" $ do
58 let l1 = Proxy :: Proxy ("hello" :> Capture "name" String :> Delete '[JSON] ())
53 let l1 = Proxy :: Proxy ("hello" :> Capture "name" String :> Delete '[JSON] ())
59 apiLink l1 "hi" `shouldBeURI` "hello/hi"
54 apiLink l1 "hi" `shouldBeURI` "hello/hi"
60
55
@@ -63,25 +58,13 @@ spec = describe "Servant.Utils.Links" $ do
63 :> Delete '[JSON] ())
58 :> Delete '[JSON] ())
64 apiLink l2 "bye" (Just True) `shouldBeURI` "hello/bye?capital=true"
59 apiLink l2 "bye" (Just True) `shouldBeURI` "hello/bye?capital=true"
65
60
66− let l3 = Proxy :: Proxy ("parent" :> MatrixParams "name" String
67− :> "child"
68− :> MatrixParam "gender" String
69− :> Get '[JSON] String)
70− apiLink l3 ["Hubert?x=;&", "Cumberdale"] (Just "Edward?")
71− `shouldBeURI` "parent;name[]=Hubert%3Fx%3D%3B%26;\
72− \name[]=Cumberdale/child;gender=Edward%3F"
73
61
74− it "Generates correct links for query and matrix flags" $ do
62+ it "Generates correct links for query flags" $ do
75 let l1 = Proxy :: Proxy ("balls" :> QueryFlag "bouncy"
63 let l1 = Proxy :: Proxy ("balls" :> QueryFlag "bouncy"
76 :> QueryFlag "fast" :> Delete '[JSON] ())
64 :> QueryFlag "fast" :> Delete '[JSON] ())
77 apiLink l1 True True `shouldBeURI` "balls?bouncy&fast"
65 apiLink l1 True True `shouldBeURI` "balls?bouncy&fast"
78 apiLink l1 False True `shouldBeURI` "balls?fast"
66 apiLink l1 False True `shouldBeURI` "balls?fast"
79
67
80− let l2 = Proxy :: Proxy ("ducks" :> MatrixFlag "yellow"
81− :> MatrixFlag "loud" :> Delete '[JSON] ())
82− apiLink l2 True True `shouldBeURI` "ducks;yellow;loud"
83− apiLink l2 False True `shouldBeURI` "ducks;loud"
84−
85 it "Generates correct links for all of the verbs" $ do
68 it "Generates correct links for all of the verbs" $ do
86 apiLink (Proxy :: Proxy ("get" :> Get '[JSON] ())) `shouldBeURI` "get"
69 apiLink (Proxy :: Proxy ("get" :> Get '[JSON] ())) `shouldBeURI` "get"
87 apiLink (Proxy :: Proxy ("put" :> Put '[JSON] ())) `shouldBeURI` "put"
70 apiLink (Proxy :: Proxy ("put" :> Put '[JSON] ())) `shouldBeURI` "put"