How to store values generated from middleware and retrieve them from routes

138 views Asked by At

I have a wai middleware that produces two values:

  1. A request id generated randomly for each request
  2. A User from a request to another service.

Here is the code:

addRequestIdToRequestHeader' :: Application -> Application
addRequestIdToRequestHeader' app req respond = do
  rid <- nextRequestId :: IO ByteString
  user <- fetchUserByReq req :: IO User
  req' <- attachUserAndRequestIdToRequest user rid
  app req' respond

Now I have a route GET /user. Inside of this route, I’d like to have access to the request id and the User. As an example, I might just print them in the log.

main :: IO ()
main =
  scotty 8080 $ do
    get "/user" $ do
      req <- request
      rid <- liftAndCatchIO $ getRequestIdFromRequest req
      user <- liftAndCatchIO $ getUserFromRequest req
      liftAndCatchIO $ print rid
      liftAndCatchIO $ print user
      text $ username user

The question is since the request id and the User are generated from the middleware, how to access them from the route? Basically how to implement the following functions used in the above code:

attachUserAndRequestIdToRequest :: User -> ByteString -> Request -> IO Request

getRequestIdFromRequest :: Request -> IO ByteString

getUserFromRequest :: Request -> IO User

The scenario is the middleware is an Auth middleware, which forwards the request to another service for authentication and gets back the user value, which will be needed in the routes.

0

There are 0 answers