【问题标题】:compojure routes : How to call a function with dependencies from a route?compojure 路由:如何从路由调用具有依赖关系的函数?
【发布时间】:2022-02-07 19:18:45
【问题描述】:

这个想法是在路由匹配时调用某个函数。该函数具有依赖项。我是 clojure 和 compojure 的新手,这种方法可能是错误的。 但是,这仍然是我努力实现的目标。

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

由于我没有找到使用defroutes 的方法,因此我尝试“动态”设置路线。

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

当我使用这样定义的路线启动码头时,

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

每次调用都会导致异常:

java.lang.NullPointerException: Response map is nil

有没有办法使用defroutes和调用函数来注入依赖项,或者可以按照我尝试的方式进行操作,但我做错了?

【问题讨论】:

    标签: dependency-injection routes clojure compojure


    【解决方案1】:

    当您返回未实现compojure.response/Renderable 协议的数据时,compojure 不知道如何呈现它,因此它希望您的结果是整个响应映射。

    更多详情可以查看in the compojure documentation

    因此,您要做的就是为您的数据实现Renderable,或者自己创建ring 响应(可能使用某些库),就像他们在ring.util.response 中所做的那样

    【讨论】:

    • 感谢您的回答。我看到的 NPE 是由浏览器请求收藏图标引起的。我没有看到任何结果的事实是由于我的服务将 id 期望为整数而不是字符串。但是您的回答帮助我采取了另一种方法,现在它正在按预期工作。
    猜你喜欢
    • 2011-02-09
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2012-10-11
    • 2018-04-22
    • 1970-01-01
    • 2014-03-25
    相关资源
    最近更新 更多