{- |Description: Combinator for Servant to allow Handlers access to
  the raw path from the WAI request.
-}
module Servant.API.RawPathInfo where

import Data.ByteString (ByteString)
import Network.Wai
import Servant
import Servant.Server.Internal.Delayed (passToServer)

{- |
  @RawPathInfo@ provides handlers access to the raw, unparsed path
  information the WAI request.

  If you wish to get the path segments, you can either use the
  @PathInfo@ combinator in @Servant.API.PathInfo@ or parse it yourself
  with @Network.HTTP.Types.decodePathSegments@

  Example:

@
import Data.ByteString (ByteString)
import Control.Monad.IO.Class (liftIO)
import Servant
import ServantExtras.RawPathInfo

type MyAPI = "my-path-info-endpoint"
           :> RawPathInfo
           :> Get '[JSON] NoContent

myServer :: Server MyAPI
myServer = queryEndpointHandler
 where
   queryEndpointHandler :: ByteString -> Handler NoContent
   queryEndpointHandler rawPath = do
     case rawPath of
      "/my-path-info-endpoint" -> do
        liftIO $ print "Servant routed us to the right place!"
        pure NoContent
      _ -> do
        liftIO $ print "My example has a bug!"
        throwError err400 { errBody = "Patches accepted!" }
@
-}
data RawPathInfo

instance HasServer api ctx => HasServer (RawPathInfo :> api) ctx where
  type ServerT (RawPathInfo :> api) m = ByteString -> ServerT api m

  hoistServerWithContext :: forall (m :: * -> *) (n :: * -> *).
Proxy (RawPathInfo :> api)
-> Proxy ctx
-> (forall x. m x -> n x)
-> ServerT (RawPathInfo :> api) m
-> ServerT (RawPathInfo :> api) n
hoistServerWithContext Proxy (RawPathInfo :> api)
_ Proxy ctx
ctx forall x. m x -> n x
nt ServerT (RawPathInfo :> api) m
server =
    forall {k} (api :: k) (context :: [*]) (m :: * -> *) (n :: * -> *).
HasServer api context =>
Proxy api
-> Proxy context
-> (forall x. m x -> n x)
-> ServerT api m
-> ServerT api n
hoistServerWithContext (forall {k} (t :: k). Proxy t
Proxy @api) Proxy ctx
ctx forall x. m x -> n x
nt forall b c a. (b -> c) -> (a -> b) -> a -> c
. ServerT (RawPathInfo :> api) m
server
  route :: forall env.
Proxy (RawPathInfo :> api)
-> Context ctx
-> Delayed env (Server (RawPathInfo :> api))
-> Router env
route Proxy (RawPathInfo :> api)
_ Context ctx
ctx Delayed env (Server (RawPathInfo :> api))
server =
    forall {k} (api :: k) (context :: [*]) env.
HasServer api context =>
Proxy api
-> Context context -> Delayed env (Server api) -> Router env
route (forall {k} (t :: k). Proxy t
Proxy @api) Context ctx
ctx forall a b. (a -> b) -> a -> b
$
      Delayed env (Server (RawPathInfo :> api))
server forall env a b.
Delayed env (a -> b) -> (Request -> a) -> Delayed env b
`passToServer` \Request
req ->
        Request -> ByteString
rawPathInfo Request
req