Fork me on GitHub
#reitit
<
2023-06-02
>
jmckitrick11:06:24

Suppose I have a large stack of middleware for my app, and I have one function that performs a request transformation early in the chain before coercion etc happens. But I only want this applied to a small set of functions. It seems the middleware function should be able to accept a boolean to conditionalize the logic internally, but I can’t seem to figure out how to call it at the router where I want it to apply. It seems like :middleware [wrap-my-request true] but this doesn’t seem to fit the reitit model, or I’m not applying it correctly. What am I missing?

p-himik12:06:01

If that middleware could be the last in the chain, it could be attached to the resource itself. Since that's not your case, there most reasonable option is to create a compiled middleware and include it as one of the first in the main chain: https://cljdoc.org/d/metosin/reitit/0.7.0-alpha4/doc/ring/compiling-middleware The boolean parameter that you describe can be used as :middleware [[wrap true]], but it will be just a parameter to the middleware function - it won't help you conditionally enable it for specific endpoints. Another, less direct, approach is to transform the middleware chain with a transformer. But if compiled middleware works for you (I don't see a reason why it wouldn't), you should use that instead.

jmckitrick13:06:36

I’ll try the compiled middleware, I just wasn’t aware I could apply it in the stack of app middleware as well as on a specific endpoint. I guess it’s no difference, it’s data all the way down.

jmckitrick13:06:31

But I still thought the boolean parameter could have conditionalized the behavior in each endpoint, even if it ended up called for each one of them

p-himik13:06:52

The boolean parameter is there just for convenience, AFAICT [wrap true] is not different from #(wrap % true). So that boolean arg will be static, you won't be able to make it conditional based on the resource or anything else. You can make a middleware conditional based on some data in the request, but that would be logic internal to the middleware itself.

jmckitrick13:06:04

OK got it. That makes sense.

jmckitrick14:06:27

That did the trick! Thanks!

👍 2