Clojure compojure middleware and arrow syntax

I am trying to understand compojure middlewares:

The following code is from the layout template :

(def app
  (wrap-defaults app-routes site-defaults))

      

Is this equivalent to the following?

(def app
  (-> app-routes
      (wrap-defaults api-defaults)))

      

I'm not sure about this, as the following code my-middleware2

calls beforemy-middleware1

(def app
  (-> api-routes
      (wrap-defaults api-defaults)
      (my-middleware1)
      (my-middleware2)))

      

+3


source to share


1 answer


You're right:

(def app
  (wrap-defaults app-routes site-defaults))

      

Equivalent to:

(def app
  (-> app-routes
      (wrap-defaults api-defaults)))

      

The arrow is called Thread-First Macro and allows you to write nested s-expressions in a linear fashion.

In your second example, it makes sense what my-middleware2

is called before my-middleware1

when the HTTP request comes in. You create the Ring Handler without calling middleware directly.



(def app
  (-> api-routes
    (wrap-defaults api-defaults)
    my-middleware1
    my-middleware2))

      

Expands to:

(def app
  (my-middleware2 (my-middleware1 (wrap-defaults app-routes api-defaults))))

      

When an HTTP request arrives, my-middleware2

processes it first, does something (that is, retrieves the session data), and then passes it along with the next middleware until one of them returns an HTTP response.

Note. I took the parens out of (my-middleware1)

and (my-middleware2)

. When used like this, it means that it my-middlware1

is a function that, when called with no arguments, returns a middleware function. This may be what you wanted, but this is not a common practice.

+3


source







All Articles