-- |
--
-- Since 3.0.9
module Network.Wai.Middleware.Routed
    ( routedMiddleware
    , hostedMiddleware
    ) where

import Data.ByteString (ByteString)
import Data.Text (Text)
import Network.Wai

-- | Apply a middleware based on a test of pathInfo
--
-- example:
--
-- > let corsify = routedMiddleWare ("static" `elem`) addCorsHeaders
--
-- Since 3.0.9
routedMiddleware :: ([Text] -> Bool) -- ^ Only use middleware if this pathInfo test returns True
                 -> Middleware -- ^ middleware to apply the path prefix guard to
                 -> Middleware -- ^ modified middleware
routedMiddleware :: ([Text] -> Bool) -> Middleware -> Middleware
routedMiddleware [Text] -> Bool
pathCheck Middleware
middle Application
app Request
req
  | [Text] -> Bool
pathCheck (Request -> [Text]
pathInfo Request
req) = Middleware
middle Application
app Request
req
  | Bool
otherwise                = Application
app Request
req

-- | Only apply the middleware to certain hosts
--
-- Since 3.0.9
hostedMiddleware :: ByteString -- ^ Domain the middleware applies to
                 -> Middleware -- ^ middleware to apply the path prefix guard to
                 -> Middleware -- ^ modified middleware
hostedMiddleware :: ByteString -> Middleware -> Middleware
hostedMiddleware ByteString
domain Middleware
middle Application
app Request
req
  | ByteString -> Request -> Bool
hasDomain ByteString
domain Request
req = Middleware
middle Application
app Request
req
  | Bool
otherwise            = Application
app Request
req

hasDomain :: ByteString -> Request -> Bool
hasDomain :: ByteString -> Request -> Bool
hasDomain ByteString
domain Request
req = Bool -> (ByteString -> Bool) -> Maybe ByteString -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
domain) Maybe ByteString
mHost
  where mHost :: Maybe ByteString
mHost = Request -> Maybe ByteString
requestHeaderHost Request
req