Middleware Patterns

MikaelAmborn edited this page Mar 5, 2015 · 8 revisions

Adding keys to the request map

Keys can be added to the request map to pass additonal information to the handler and other middleware.

Here is an example that adds a :user key to the request, if there is a user ID in the session.

(defn wrap-user [handler]
  (fn [request]
    (if-let [user-id (-> request :session :user-id)]
      (let [user (get-user-by-id user-id)]
        (handler (assoc request :user user)))
      (handler request))))

The get-user-by-id function will depend on how the application stores user information.

Wrapping the handler in a binding

Often it is useful to bind an object to a var for the duration of a handler.

Here is an example that wraps a handler in the (now deprecated) clojure.contrib.sql/with-connection macro.

(defn wrap-sql-connection [handler db-spec]
  (fn [request]
    (with-connection db-spec
      (handler request))))

Conditionally executing the handler

(defn wrap-auth [handler]
  (fn [request]
    (if (authorized? request)
      (handler request)
      (-> (response "Access Denied")
          (status 403)))))
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.