Adding middleware to the routes

I would like to add an EDN parser middleware to the server generated by chestnut but I can’t seem to get it to work.

In a tutorial they do the following.

(defn parse-edn-body [handler]
  (fn [request]
      (handler (if-let [body (:body request)]
                       (assoc request
                              :edn-body (read-inputstream-edn body))
                       request))))

(def handler 
     (-> routes
         parse-edn-body))

The chestnut server has

(def http-handler
     (if is-dev?
         (reload/wrap-reload (api #'routes))
         (api routes)))

I’m not sure how this middleware stuff works or where to add the EDN parser. Any help would be appreciated.

Try this

(def http-handler
  (parse-edn-body
     (if is-dev?
         (reload/wrap-reload (api #'routes))
         (api routes))))

A handler is a function that takes a http request, and returns the response. Middleware is a function that takes a handler (so a request->response function) and returns a new handler. So you wrap the existing handler in a call to the parse-edn-body middleware.

Hope that helps.

1 Like

Yeah that totally makes sense. Thanks! Also chestnut is freakin awesome, thanks for that too!

1 Like

It’s a pleasure :slight_smile: :slight_smile:

Hi,

I am trying do same things, but:

photos.server=> (run)

CompilerException java.lang.RuntimeException: Unable to resolve symbol: run in this context, compiling:(/private/var/folders/rc/y5p0pv054xb20rtgwhzx5pzc0000gn/T/form-init1884776825299031157.clj:1:1)

My server.clj contains:

(defn read-inputstream-edn [input]
  (edn/read
   {:eof nil}
   (java.io.PushbackReader.
    (java.io.InputStreamReader. input "UTF-8"))))

(defn parse-edn-body [handler]
  (fn [request]
      (handler (if-let [body (:body request)]
                       (assoc request
                              :edn-body (read-inputstream-edn body))
                       request))))

(def http-handler
  (parse-edn-body
   (if is-dev?
     (reload/wrap-reload (wrap-defaults #'routes api-defaults))
     (wrap-defaults routes api-defaults)))

What I am doing wrong here.

Thanks in Advance

Look carefully at the output when the REPL boots. Unable to resolve symbol: run is usually a symptom that there’s an error in the code, so things aren’t loaded properly.

If you can’t figure it out then push your app to github and I’ll have a look.

Sorry, I had a typo error on my namespace declaration. :slight_smile: thanks

I used fogus/ring-edn

(def http-handler
  (let [handler (-> routes
                    (wrap-defaults api-defaults)
                    (wrap-edn-params))] 
    (if is-dev? (reload/wrap-reload handler) handler)))