on master help sign in
Remove MatrixParam.

In servant, servant-server, and servant-client.

commitafc76b8f6cf023840ce17ccb583e8e5cad7fabe4 authorJulian K. Arni <jkarni@gmail.com> dateThu 8 Oct 2015, 22:40 (11 years ago) parent6ef59de
13 files changed+22−547
servant-client/src/Servant/Client.hs−128 servant-client/src/Servant/Common/Req.hs−7 servant-client/test/Servant/ClientSpec.hs+1−29 servant-server/servant-server.cabal−1 servant-server/src/Servant/Server/Internal.hs+8−124 servant-server/src/Servant/Server/Internal/PathInfo.hs−38 servant-server/src/Servant/Server/Internal/Router.hs+2−3 servant-server/test/Servant/ServerSpec.hs+7−91 servant/servant.cabal−1 servant/src/Servant/API.hs−4 servant/src/Servant/API/MatrixParam.hs−51 servant/src/Servant/Utils/Links.hs+1−50 servant/test/Servant/Utils/LinksSpec.hs+3−20
servant-client/src/Servant/Client.hs−128
@@ -477,134 +477,6 @@ instance (KnownSymbol sym, HasClient sublayout)
477477
478478 where paramname = cs $ symbolVal (Proxy :: Proxy sym)
479479
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)
608480
609481-- | Pick a 'Method' and specify where the server you want to query is. You get
610482-- back the full `Response`.
servant-client/src/Servant/Common/Req.hs−7
@@ -72,13 +72,6 @@ appendToPath :: String -> Req -> Req
7272appendToPath p req =
7373 req { reqPath = reqPath req ++ "/" ++ p }
7474
75−appendToMatrixParams :: String
76− -> Maybe String
77− -> Req
78− -> Req
79−appendToMatrixParams pname pvalue req =
80− req { reqPath = reqPath req ++ ";" ++ pname ++ maybe "" ("=" ++) pvalue }
81−
8275appendToQueryString :: Text -- ^ param name
8376 -> Maybe Text -- ^ param value
8477 -> Req
servant-client/test/Servant/ClientSpec.hs+1−29
@@ -96,9 +96,6 @@ type Api =
9696 :<|> "param" :> QueryParam "name" String :> Get '[FormUrlEncoded,JSON] Person
9797 :<|> "params" :> QueryParams "names" String :> Get '[JSON] [Person]
9898 :<|> "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
10299 :<|> "rawSuccess" :> Raw
103100 :<|> "rawFailure" :> Raw
104101 :<|> "multiple" :>
@@ -124,12 +121,6 @@ server = serve api (
124121 Nothing -> throwE $ ServantErr 400 "missing parameter" "" [])
125122 :<|> (\ names -> return (zipWith Person names [0..]))
126123 :<|> 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
133124 :<|> (\ _request respond -> respond $ responseLBS ok200 [] "rawSuccess")
134125 :<|> (\ _request respond -> respond $ responseLBS badRequest400 [] "rawFailure")
135126 :<|> (\ a b c d -> return (a, b, c, d))
@@ -198,26 +189,7 @@ sucessSpec = beforeAll (startWaiApp server) $ afterAll endWaiApp $ do
198189 let getQueryFlag = getNth (Proxy :: Proxy 6) $ client api baseUrl manager
199190 (left show <$> runExceptT (getQueryFlag flag)) `shouldReturn` Right flag
200191
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
220− let getRawSuccess = getNth (Proxy :: Proxy 10) $ client api baseUrl manager
192+ it "Servant.API.Raw on success" $ do
221193 res <- runExceptT (getRawSuccess methodGet)
222194 case res of
223195 Left e -> assertFailure $ show e
servant-server/servant-server.cabal−1
@@ -37,7 +37,6 @@ library
3737 Servant.Server
3838 Servant.Server.Internal
3939 Servant.Server.Internal.Enter
40− Servant.Server.Internal.PathInfo
4140 Servant.Server.Internal.Router
4241 Servant.Server.Internal.RoutingApplication
4342 Servant.Server.Internal.ServantErr
servant-server/src/Servant/Server/Internal.hs+8−124
@@ -14,7 +14,6 @@
1414
1515module Servant.Server.Internal
1616 ( module Servant.Server.Internal
17− , module Servant.Server.Internal.PathInfo
1817 , module Servant.Server.Internal.Router
1918 , module Servant.Server.Internal.RoutingApplication
2019 , module Servant.Server.Internal.ServantErr
@@ -31,8 +30,6 @@ import Data.Maybe (mapMaybe, fromMaybe)
3130import Data.String (fromString)
3231import Data.String.Conversions (cs, (<>), ConvertibleStrings)
3332import Data.Text (Text)
34−import qualified Data.Text as T
35−import Data.Text.Encoding (encodeUtf8)
3633import Data.Typeable
3734import GHC.TypeLits (KnownSymbol, symbolVal)
3835import Network.HTTP.Types hiding (Header, ResponseHeaders)
@@ -41,11 +38,10 @@ import Network.Wai (Application, lazyRequestBody,
4138 rawQueryString, requestHeaders,
4239 requestMethod, responseLBS, remoteHost,
4340 isSecure, vault, httpVersion, Response,
44− Request)
41+ Request, pathInfo)
4542import Servant.API ((:<|>) (..), (:>), Capture,
4643 Delete, Get, Header,
47− IsSecure(..), MatrixFlag, MatrixParam,
48− MatrixParams, Patch, Post, Put,
44+ IsSecure(..), Patch, Post, Put,
4945 QueryFlag, QueryParam, QueryParams,
5046 Raw, RemoteHost, ReqBody, Vault)
5147import Servant.API.ContentTypes (AcceptHeader (..),
@@ -54,7 +50,6 @@ import Servant.API.ContentTypes (AcceptHeader (..),
5450import Servant.API.ResponseHeaders (Headers, getResponse, GetHeaders,
5551 getHeaders)
5652
57−import Servant.Server.Internal.PathInfo
5853import Servant.Server.Internal.Router
5954import Servant.Server.Internal.RoutingApplication
6055import Servant.Server.Internal.ServantErr
@@ -548,123 +543,6 @@ instance (KnownSymbol sym, HasServer sublayout)
548543 examine v | v == "true" || v == "1" || v == "" = True
549544 | otherwise = False
550545
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−
668546-- | Just pass the request to the underlying application and serve its response.
669547--
670548-- Example:
@@ -762,5 +640,11 @@ instance HasServer api => HasServer (HttpVersion :> api) where
762640 route Proxy subserver = WithRequest $ \req ->
763641 route (Proxy :: Proxy api) (feedTo subserver $ httpVersion req)
764642
643+pathIsEmpty :: Request -> Bool
644+pathIsEmpty = go . pathInfo
645+ where go [] = True
646+ go [""] = True
647+ go _ = False
648+
765649ct_wildcard :: B.ByteString
766650ct_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
77import Data.Monoid ((<>))
88import Data.Text (Text)
99import Network.Wai (Request, Response, pathInfo)
10−import Servant.Server.Internal.PathInfo
1110import Servant.Server.Internal.RoutingApplication
1211
1312type Router = Router' RoutingApplication
@@ -59,14 +58,14 @@ runRouter :: Router -> RoutingApplication
5958runRouter (WithRequest router) request respond =
6059 runRouter (router request) request respond
6160runRouter (StaticRouter table) request respond =
62− case processedPathInfo request of
61+ case pathInfo request of
6362 first : rest
6463 | Just router <- M.lookup first table
6564 -> let request' = request { pathInfo = rest }
6665 in runRouter router request' respond
6766 _ -> respond $ failWith NotFound
6867runRouter (DynamicRouter fun) request respond =
69− case processedPathInfo request of
68+ case pathInfo request of
7069 first : rest
7170 -> let request' = request { pathInfo = rest }
7271 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)
3838import Test.Hspec.Wai (get, liftIO, matchHeaders,
3939 matchStatus, post, request,
4040 shouldRespondWith, with, (<:>))
41−import Servant.API ((:<|>) (..), (:>),
42− addHeader, Capture,
43− Delete, Get, Header (..), Headers,
44− HttpVersion, IsSecure(..), JSON, MatrixFlag,
45− MatrixParam, MatrixParams, Patch, PlainText,
46− Post, Put, RemoteHost, QueryFlag, QueryParam,
47− QueryParams, Raw, ReqBody)
41+import Servant.API ((:<|>) (..), (:>), Capture, Delete,
42+ Get, Header (..), Headers,
43+ HttpVersion, IsSecure (..), JSON,
44+ Patch, PlainText, Post, Put,
45+ QueryFlag, QueryParam, QueryParams,
46+ Raw, RemoteHost, ReqBody,
47+ addHeader)
4848import Servant.Server (Server, serve, ServantErr(..), err404)
4949import Servant.Server.Internal.Router
5050 (tweakResponse, runRouter,
@@ -95,7 +95,6 @@ spec = do
9595 putSpec
9696 patchSpec
9797 queryParamSpec
98− matrixParamSpec
9998 headerSpec
10099 rawSpec
101100 unionSpec
@@ -275,89 +274,6 @@ queryParamSpec = do
275274 name = "Alice"
276275 }
277276
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−
361277type PostApi =
362278 ReqBody '[JSON] Person :> Post '[JSON] Integer
363279 :<|> "bla" :> ReqBody '[JSON] Person :> Post '[JSON] Integer
servant/servant.cabal−1
@@ -37,7 +37,6 @@ library
3737 Servant.API.Post
3838 Servant.API.Put
3939 Servant.API.QueryParam
40− Servant.API.MatrixParam
4140 Servant.API.Raw
4241 Servant.API.RemoteHost
4342 Servant.API.ReqBody
servant/src/Servant/API.hs−4
@@ -17,8 +17,6 @@ module Servant.API (
1717 -- | Retrieving parameters from the query string of the 'URI': @'QueryParam'@
1818 module Servant.API.ReqBody,
1919 -- | Accessing the request body as a JSON-encoded type: @'ReqBody'@
20− module Servant.API.MatrixParam,
21− -- | Retrieving matrix parameters from the 'URI' segment: @'MatrixParam'@
2220 module Servant.API.RemoteHost,
2321 -- | Retrieving the IP of the client
2422 module Servant.API.IsSecure,
@@ -71,8 +69,6 @@ import Servant.API.Get (Get)
7169import Servant.API.Header (Header (..))
7270import Servant.API.HttpVersion (HttpVersion (..))
7371import Servant.API.IsSecure (IsSecure (..))
74−import Servant.API.MatrixParam (MatrixFlag, MatrixParam,
75− MatrixParams)
7672import Servant.API.Patch (Patch)
7773import Servant.API.Post (Post)
7874import 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
117117import Servant.API.Capture ( Capture )
118118import Servant.API.ReqBody ( ReqBody )
119119import Servant.API.QueryParam ( QueryParam, QueryParams, QueryFlag )
120−import Servant.API.MatrixParam ( MatrixParam, MatrixParams, MatrixFlag )
121120import Servant.API.Header ( Header )
122121import Servant.API.Get ( Get )
123122import Servant.API.Post ( Post )
@@ -173,9 +172,6 @@ type family IsElem endpoint api :: Constraint where
173172 IsElem sa (QueryParam x y :> sb) = IsElem sa sb
174173 IsElem sa (QueryParams x y :> sb) = IsElem sa sb
175174 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
179175 IsElem (Get ct typ) (Get ct' typ) = IsSubList ct ct'
180176 IsElem (Post ct typ) (Post ct' typ) = IsSubList ct ct'
181177 IsElem (Put ct typ) (Put ct' typ) = IsSubList ct ct'
@@ -192,10 +188,9 @@ type family IsSubList a b :: Constraint where
192188 IsSubList (x ': xs) y = IsSubList '[x] y `And` IsSubList xs y
193189
194190-- Phantom types for Param
195−data Matrix
196191data Query
197192
198−-- | Query/Matrix param
193+-- | Query param
199194data Param a
200195 = SingleParam String Text
201196 | ArrayElemParam String Text
@@ -209,21 +204,6 @@ addQueryParam :: Param Query -> Link -> Link
209204addQueryParam qp l =
210205 l { _queryParams = _queryParams l <> [qp] }
211206
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−
227207linkURI :: Link -> URI
228208linkURI (Link segments q_params) =
229209 URI mempty -- No scheme (relative)
@@ -300,35 +280,6 @@ instance (KnownSymbol sym, HasLink sub)
300280 where
301281 k = symbolVal (Proxy :: Proxy sym)
302282
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−
332283-- Misc instances
333284instance HasLink sub => HasLink (ReqBody ct a :> sub) where
334285 type MkLink (ReqBody ct a :> sub) = MkLink sub
servant/test/Servant/Utils/LinksSpec.hs+3−20
@@ -11,14 +11,10 @@ import Data.Proxy ( Proxy(..) )
1111import Servant.API
1212
1313type TestApi =
14− -- Capture and query/matrix params
14+ -- Capture and query params
1515 "hello" :> Capture "name" String :> QueryParam "capital" Bool :> Delete '[JSON] ()
1616
17− :<|> "parent" :> MatrixParams "name" String :> "child"
18− :> MatrixParam "gender" String :> Get '[JSON] String
19−
2017 -- Flags
21− :<|> "ducks" :> MatrixFlag "yellow" :> MatrixFlag "loud" :> Delete '[JSON] ()
2218 :<|> "balls" :> QueryFlag "bouncy" :> QueryFlag "fast" :> Delete '[JSON] ()
2319
2420 -- All of the verbs
@@ -34,7 +30,6 @@ type TestLink3 = "parent" :> "child" :> Get '[JSON] String
3430
3531type BadTestLink = "hallo" :> "hi" :> Get '[JSON] Bool
3632type BadTestLink2 = "greet" :> Get '[PlainText] Bool
37−type BadTestLink3 = "parent" :> "child" :> MatrixFlag "male" :> Get '[JSON] String
3833
3934type BadTestLink' = "hello" :> "hi" :> Get '[OctetStream] Bool
4035type BadTestLink'2 = "greet" :> Get '[OctetStream] Bool
@@ -54,7 +49,7 @@ shouldBeURI link expected =
5449
5550spec :: Spec
5651spec = 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
5853 let l1 = Proxy :: Proxy ("hello" :> Capture "name" String :> Delete '[JSON] ())
5954 apiLink l1 "hi" `shouldBeURI` "hello/hi"
6055
@@ -63,25 +58,13 @@ spec = describe "Servant.Utils.Links" $ do
6358 :> Delete '[JSON] ())
6459 apiLink l2 "bye" (Just True) `shouldBeURI` "hello/bye?capital=true"
6560
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"
7361
74− it "Generates correct links for query and matrix flags" $ do
62+ it "Generates correct links for query flags" $ do
7563 let l1 = Proxy :: Proxy ("balls" :> QueryFlag "bouncy"
7664 :> QueryFlag "fast" :> Delete '[JSON] ())
7765 apiLink l1 True True `shouldBeURI` "balls?bouncy&fast"
7866 apiLink l1 False True `shouldBeURI` "balls?fast"
7967
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−
8568 it "Generates correct links for all of the verbs" $ do
8669 apiLink (Proxy :: Proxy ("get" :> Get '[JSON] ())) `shouldBeURI` "get"
8770 apiLink (Proxy :: Proxy ("put" :> Put '[JSON] ())) `shouldBeURI` "put"