Haskell wai middleware - how to run application if 404 is returned from the first application?

135 views Asked by At

I'm trying to 'join' two wai Applications together. Essentially the first app will either serve a 404 Not found response or a response that is not a 404 Not found response. I'd like to add a second application that will attempt to process the request if the first case (first application returns a 404) is present.

However looking at the type of Application:

type Application = Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived

It's not clear how to inspect the response? As wouldn't I just end up with ResponseRecived as the end result - which does not seem to contain any response code. As seen below:

xyzMiddle :: (Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived) ->
             (Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived)
xyzMiddle app req respond = do
  zzz <- (app req respond)
  pure zzz

How could I implement this? And or, what am I failing to understand in the above?

1

There are 1 answers

0
Chris Stryczynski On BEST ANSWER

I overlooked this (Response -> IO ResponseReceived) as that is in the IO context - this is where we can run the second application. Which means, to inspect the Response we can do something like:

xyzMiddle :: (Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived) ->
             Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived
xyzMiddle app req respond = app req (\r -> do
  print $ show $ responseStatus r
  respond r)