1

我正在使用 compojure-api,我正在寻找一个函数,给定我的 api 路由结构和请求,返回该请求的路由记录(或:名称),而不应用其处理程序。

我已经能够在 compojure.api.routes/path-for 中找到与我正在寻找的相反的东西,给定一个 :name,它会返回相应路由的路径。在同一个命名空间中,还有像 get-routes 这样看起来很有前途的功能,但我还没有找到我正在寻找的东西。

换句话说,给定这个简单的例子

(defapi my-api
  (context "/" []
    (GET "/myroute" request
      :name :my-get
      (ok))
    (POST "/myroute" request
      :name :my-post
      (ok))))

我正在寻找一个像这样工作的函数 foo

(foo my-api (mock/request :get "/myroute"))
;; => #Route{:path "/myroute", :method :get, :info {:name :my-get, :public {:x-name :my-get}}}
;; or
;; => :my-get

有任何想法吗?

4

1 回答 1

3

my-api is defined as a Route Record, so you can evaluate it at the repl to see what it looks like:

#Route{:info {:coercion :schema},
       :childs [#Route{:childs [#Route{:path "/",
                                       :info {:static-context? true},
                                       :childs [#Route{:path "/myroute",
                                                       :method :get,
                                                       :info {:name :my-get, :public {:x-name :my-get}}}
                                                #Route{:path "/myroute",
                                                       :method :post,
                                                       :info {:name :my-post, :public {:x-name :my-post}}}]}]}]}

There are helpers in compojure.api.routes to transform the structure:

(require '[compojure.api.routes :as routes])

(routes/get-routes my-api)
; [["/myroute" :get {:coercion :schema, :static-context? true, :name :my-get, :public {:x-name :my-get}}]
;  ["/myroute" :post {:coercion :schema, :static-context? true, :name :my-post, :public {:x-name :my-post}}]]

, which effectively flattens the route tree while retaining the order. For reverse routing there is:

(-> my-api
    routes/get-routes
    routes/route-lookup-table)
; {:my-get {"/myroute" {:method :get}}
;  :my-post {"/myroute" {:method :post}}}

More utilities can be added if needed.

Hope this helps.

于 2017-11-15T06:26:06.143 回答