Fork me on GitHub
#reitit
<
2022-10-17
>
Rikard Mustajärvi16:10:56

Hi! Thanks for creating Reitit. Is there a way to distinct middlewares so that they don't get applied multiple times (in my case it's a side effecting middleware). A small example showing the issue is:

(let [middleware {:name :this-middleware-gets-executed-twice
                  :wrap identity}
      router-options {:data {:middleware [middleware]}}
      router (ring/router [["/one" {:handler identity
                                    :middleware [middleware]}]]
                          router-options)
      comp-routes (reitit.core/compiled-routes router)]
  (clojure.pprint/pprint (-> comp-routes first second )))
Which outputs
{:middleware
 [{:name :this-middleware-gets-executed-twice,
   :wrap
   #object[clojure.core$identity 0x746beac "clojure.core$identity@746beac"]}
  {:name :this-middleware-gets-executed-twice,
   :wrap
   #object[clojure.core$identity 0x746beac "clojure.core$identity@746beac"]}],
 :handler
 #object[clojure.core$identity 0x746beac "clojure.core$identity@746beac"]}
This seems to happen in the route compilation process when the router is created. I guess it's the default append strategy used by meta-merge, but I'm not sure where I should inject logic to de-dup it.

valtteri18:10:24

Hi! I’d first look into why the the middleware goes twice into the route-data in first place and see if there’s a simple way to just avoid doing it. If that doesn’t work out, it’s possible to manipulate the middleware chain https://cljdoc.org/d/metosin/reitit/0.5.18/doc/ring/transforming-middleware-chain

onetom07:10:34

(-> comp-routes first second :middleware (->> (map :name) frequencies (filter (fn [[_mw-name cnt]] (< 1 cnt)))))
would should u what's duplicated and how many times