【问题标题】:Clojure - combine pedestal routesClojure - 结合基座路线
【发布时间】:2016-02-03 10:00:20
【问题描述】:

如何在 Pedestal 中合并路线?

(defroutes api-routes [...])
(defroutes site-routes [...])
(combine-routes api-routes site-routes) ;; should be a valid route as well

注意:这是一个与Combining routes in Compojure 类似的问题,但针对的是 Pedestal。

【问题讨论】:

    标签: clojure pedestal


    【解决方案1】:

    就这么简单

    (def all-routes (concat api-routes site-routes))
    

    解释从https://github.com/pedestal/pedestal/blob/master/guides/documentation/service-routing.md#defining-route-tables这里开始,据说

    路由表只是一个数据结构;在我们的例子中,它是一系列地图。

    基座团队将地图序列路由表称为详细格式,他们设计了简洁格式的路由表,这就是我们的供应给defroutedefroute 然后将我们的简洁格式转换为详细格式。

    你可以在repl中自己检查

    ;; here we supply a terse route format to defroutes
    > (defroutes routes
      [[["/" {:get home-page}
         ["/hello" {:get hello-world}]]]]) 
    ;;=> #'routes
    
    ;; then we pretty print the verbose route format
    > (pprint routes)
    ;;=>
    ({:path-parts [""],
      :path-params [],
      :interceptors
      [{:name :mavbozo-pedestal.core/home-page,
        :enter
        #object[io.pedestal.interceptor$eval7317$fn__7318$fn__7319 0x95d91f4 "io.pedestal.interceptor$eval7317$fn__7318$fn__7319@95d91f4"],
        :leave nil,
        :error nil}],
      :path "/",
      :method :get,
      :path-re #"/\Q\E",
      :route-name :mavbozo-pedestal.core/home-page}
     {:path-parts ["" "hello"],
      :path-params [],
      :interceptors
      [{:name :mavbozo-pedestal.core/hello-world,
        :enter
        #object[io.pedestal.interceptor$eval7317$fn__7318$fn__7319 0x4a168461 "io.pedestal.interceptor$eval7317$fn__7318$fn__7319@4a168461"],
        :leave nil,
        :error nil}],
      :path "/hello",
      :method :get,
      :path-re #"/\Qhello\E",
      :route-name :mavbozo-pedestal.core/hello-world})
    

    所以,由于基座路线只是一系列地图,我们可以很容易地将多个不重叠的路线与concat结合起来。

    这就是我喜欢基座团队遵循的 clojure 原则之一:通用数据操作,在这种情况下,详细格式化的路由表只是一个映射 - 一个普通的 clojure 数据结构可以使用常规 clojure.core 的数据结构操作函数(例如concat)进行检查和操作。即使是简洁的格式也是一种普通的 clojure 数据结构,可以通过相同的方式轻松检查和操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多