@@ -84,6 +84,7 @@ module Servant.Utils.Links (
85 -- | Note that 'URI' is from the "Network.URI" module in the @network-uri@ package.
85 -- | Note that 'URI' is from the "Network.URI" module in the @network-uri@ package.
88 -- * Adding custom types
89 -- * Adding custom types
89 , HasLink(..)
90 , HasLink(..)
@@ -108,6 +109,7 @@ import Prelude ()
108import Prelude.Compat
109import Prelude.Compat
110import Web.HttpApiData
111import Web.HttpApiData
112+import Servant.API.Alternative ( (:<|>)((:<|>)) )
111import Servant.API.BasicAuth ( BasicAuth )
113import Servant.API.BasicAuth ( BasicAuth )
112import Servant.API.Capture ( Capture, CaptureAll )
114import Servant.API.Capture ( Capture, CaptureAll )
113import Servant.API.ReqBody ( ReqBody )
115import Servant.API.ReqBody ( ReqBody )
@@ -220,6 +222,30 @@ safeLink
220 -> MkLink endpoint
222 -> MkLink endpoint
221safeLink _ endpoint = toLink endpoint (Link mempty mempty)
223safeLink _ endpoint = toLink endpoint (Link mempty mempty)
225+-- | Create all links in an API.
227+-- Note that the @api@ type must be restricted to the endpoints that have
228+-- valid links to them.
230+-- >>> type API = "foo" :> Capture "name" Text :> Get '[JSON] Text :<|> "bar" :> Capture "name" Int :> Get '[JSON] Double
231+-- >>> let fooLink :<|> barLink = allLinks (Proxy :: Proxy API)
233+-- fooLink :: Text -> Link
235+-- barLink :: Int -> Link
237+-- Note: nested APIs don't work well with this approach
239+-- >>> :kind! MkLink (Capture "nest" Char :> (Capture "x" Int :> Get '[JSON] Int :<|> Capture "y" Double :> Get '[JSON] Double))
240+-- MkLink (Capture "nest" Char :> (Capture "x" Int :> Get '[JSON] Int :<|> Capture "y" Double :> Get '[JSON] Double)) :: *
241+-- = Char -> (Int -> Link) :<|> (Double -> Link)
244+ :: forall api. HasLink api
247+allLinks api = toLink api (Link mempty mempty)
223-- | Construct a toLink for an endpoint.
249-- | Construct a toLink for an endpoint.
224class HasLink endpoint where
250class HasLink endpoint where
225 type MkLink endpoint
251 type MkLink endpoint
@@ -266,6 +292,11 @@ instance (KnownSymbol sym, HasLink sub)
267 k = symbolVal (Proxy :: Proxy sym)
293 k = symbolVal (Proxy :: Proxy sym)
295+-- :<|> instance - Generate all links at once
296+instance (HasLink a, HasLink b) => HasLink (a :<|> b) where
297+ type MkLink (a :<|> b) = MkLink a :<|> MkLink b
298+ toLink _ l = toLink (Proxy :: Proxy a) l :<|> toLink (Proxy :: Proxy b) l
269-- Misc instances
300-- Misc instances
270instance HasLink sub => HasLink (ReqBody ct a :> sub) where
301instance HasLink sub => HasLink (ReqBody ct a :> sub) where
271 type MkLink (ReqBody ct a :> sub) = MkLink sub
302 type MkLink (ReqBody ct a :> sub) = MkLink sub
@@ -313,3 +344,4 @@ instance HasLink sub => HasLink (AuthProtect tag :> sub) where
315-- >>> import Servant.API
346-- >>> import Servant.API
347+-- >>> import Data.Text (Text)