{- |Description: Provides a combinator to access the Query String in
 its raw form, from the WAI request.
-}
module Servant.API.RawQueryString where

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

{- |
  @RawQueryString@ gives handler authors a combinator to access the raw
  (that is, un-parsed) query string from the WAI request, as a
  ByteString.

  Generally speaking, you should prefer to use the @QueryString@
  combinator, but if you need access to the raw value, this combinator
  provides it.

  Example:

@
import Control.Monad.IO.Class (liftIO)
import Servant
import ServantExtras.RawQueryString

import qualified Network.HTTP.Types.Header as NTH (Header)

type MyAPI = "my-query-endpoint"
           :> RawQueryString
           :> Get '[JSON] NoContent

myServer :: Server MyAPI
myServer = queryEndpointHandler
  where
    queryEndpointHandler :: ByteString -> Handler NoContent
    queryEndpointHandler queryStr =
      -- do something with the ByteString, like pass it to a
      -- sub-process

@
-}
data RawQueryString

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

  hoistServerWithContext :: forall (m :: * -> *) (n :: * -> *).
Proxy (RawQueryString :> api)
-> Proxy ctx
-> (forall x. m x -> n x)
-> ServerT (RawQueryString :> api) m
-> ServerT (RawQueryString :> api) n
hoistServerWithContext Proxy (RawQueryString :> api)
_ Proxy ctx
ctx forall x. m x -> n x
nt ServerT (RawQueryString :> 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 (RawQueryString :> api) m
server
  route :: forall env.
Proxy (RawQueryString :> api)
-> Context ctx
-> Delayed env (Server (RawQueryString :> api))
-> Router env
route Proxy (RawQueryString :> api)
_ Context ctx
ctx Delayed env (Server (RawQueryString :> 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 (RawQueryString :> api))
server forall env a b.
Delayed env (a -> b) -> (Request -> a) -> Delayed env b
`passToServer` \Request
req ->
        Request -> ByteString
rawQueryString Request
req