Skip to content

Middleware Patterns

weavejester edited this page Sep 11, 2010 · 9 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 is 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|http://richhickey.github.com/clojure-contrib/sql-api.html#clojure.contrib.sql/with-connection] macro.

(defn wrap-sql-connection [handler db-spec]
  (fn [request]
    (with-connection db-spec
      (handler request))))
Clone this wiki locally