Akeboshiwind / tg-clj-server

A more framework-y library for use with tg-clj inspired by ring web-servers.
MIT License
3 stars 0 forks source link

Add middleware *before* routes are selected #2

Open Akeboshiwind opened 5 months ago

Akeboshiwind commented 5 months ago

Currently you can only add middleware after the routes are selected.

A case where this might be useful is adding some data to the request then routing based on that:

(defn random-select-middleware [handler]
  (fn [request]
    (handler (assoc request :selected? (rand-nth [true false])))))

(def routes
  [[:selected? #'handler]
   [(complement :selected?) #'other-handler]])

To use this middleware currently you have to build the stack yourself:

(-> router/execute-route
    ;; Other middleware
    (store/middleware {:path "store.edn"})
    (router/select-route-middleware routes)
    random-select-middleware
    invoke/middleware)
Akeboshiwind commented 5 months ago

Proposal 1

It would look something like this:

(def app
  (defaults/make-app routes {:pre-middleware [random-select-middleware]
                             :post-middleware [other-middleware]}))

Downsides:

Proposal 2

It would look something like this:

(def routes
  [[:selected? #'selected]
   [(complement :selected?) {:handler #'not-selected
                             :middleware [other-middleware]}]])

; With sketched parent data
(def routes
  [(constantly true) {:middleware [other-middleware]}
   [:selected? #'selected]
   [(complement :selected?) {:handler #'not-selected
                             :middleware [other-middleware]}]])

(def app
  (defaults/make-app routes {:middleware [random-select-middleware]}))

Downsides:

Proposal 3

Use interceptors? Not thought this through but they can re-order themselves right?

Downsides:

Akeboshiwind commented 5 months ago

Proposal 4

Deprecate defaults and instead provide a template project.

Downsides:

Akeboshiwind commented 4 months ago

Having mulled over these a bit and explored interceptors a bit more, I'm feeling Proposal 2 the most.

I.e:

My thoughts are: