Skip to content

Instantly share code, notes, and snippets.

@ivan-kleshnin
Last active December 30, 2022 05:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan-kleshnin/601503b9062ba45863d5 to your computer and use it in GitHub Desktop.
Save ivan-kleshnin/601503b9062ba45863d5 to your computer and use it in GitHub Desktop.
Brainstorming middleware ordering... Wider application though.
;; 0. Given that `app` is a RING handler
;; 1. We have 6 functions: 3 to modify requests, 3 to modify responses
;; 1.1. Request modifiers
(defn modify-request-first [handler]
(fn [request]
(println "modify-request-first") ; "println" is a placeholder for real code
(handler request)))
(defn modify-request-second [handler]
(fn [request]
(println "modify-request-second")
(handler request)))
(defn modify-request-third [handler]
(fn [request]
(println "modify-request-third")
(handler request)))
;; 1.2. Response modifiers
(defn modify-response-first [handler]
(fn [request]
(let [response (handler request)]
(println "modify-response-first")
response)))
(defn modify-response-second [handler]
(fn [request]
(let [response (handler request)]
(println "modify-response-second")
response)))
(defn modify-response-third [handler]
(fn [request]
(let [response (handler request)]
(println "modify-response-third")
response)))
;; 2. We want to get this order at output
; modify-request-first
; modify-request-second
; modify-request-third
; modify-response-first
; modify-response-second
; modify-response-third
;; 3. How function calls should be ordered?
;; 3.1. Request modifiers: outer is first
(def app
(modify-request-first
(modify-request-second
(modify-request-third app))))
;; 3.2. Requires bottom-up order with TF macro
(def app
(-> app
modify-request-third
modify-request-second
modify-request-first))
;; 3.3. Response modifiers: inner is first
(def app
(modify-response-third
(modify-response-second
(modify-response-first app))))
;; 3.4. Requires top-down order with TF macro
(def app
(-> app
modify-response-first
modify-response-second
modify-response-third))
;; 4.1. The Full Set ^_^ in wrap-style
(def app
(modify-response-third
(modify-response-second
(modify-response-first
(modify-request-first
(modify-request-second
(modify-request-third app)))))))
;; 4.2. And in TF style
(def app
(-> app
modify-request-third
modify-request-second
modify-request-first
modify-response-first
modify-response-second
modify-response-third))
;; 5. Conclusion: you cannot order handlers which do both request and response handlings in general case!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment