compojure routes : How to call a function with dependencies from a route?

141 views Asked by At

The idea is to call a certain function when a route matches. That function has dependencies . I'm new to clojure and compojure and this approach could be wrong. But still, this is what I try to achieve.

(defroutes my-routes (GET "/user/list"
                      []
                   (list-users)) ; where list-users is for example (partial list-users user-service)

Since I didn't find a way to do this with defroutes, I tried to setup the routes "dynamically".

 (defn define-routes [services]
  (routes
    (GET "/user/:id"
         [id]
      ((:show-user services) id))
    (GET "/user/list"
         []
      ((:list-users services))))

When I start jetty with the routes defined like this,

 (defn app [services]
     (j/run-jetty (define-routes services) {:port 3000 :join? false}))

every call leads to an exception:

java.lang.NullPointerException: Response map is nil

Is there a way to use defroutes and call functions where dependecies are injected or is ok to do it the way I tried, but I'm doing it wrong?

1

There are 1 answers

1
leetwinski On

When you return the data that doesn't implement compojure.response/Renderable protocol, compojure doesn't know how to render it, so it expects that your result would be the whole response map.

More details can be found in the compojure documentation

So what you have to do is either implement Renderable for your data, or create the ring response yourself (presumably with some libraries), like they do in ring.util.response