Middleware Patterns

thirdstation edited this page Nov 6, 2010 · 6 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 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)))))