【问题标题】:Typecast compojure route's id to integer automatically自动将复合路由的 id 类型转换为整数
【发布时间】:2016-06-04 21:51:14
【问题描述】:

我有这样的(GET "/photo/:id/tags/:tag-id/...")

因此对于该上下文中的每条路由,我必须将这些 id 显式类型转换为 Integer。有没有办法自动实现这一点,或者有一个共同的地方来类型转换 id 而不是每个控制器的操作?

【问题讨论】:

    标签: clojure routes parseint compojure ring


    【解决方案1】:

    您可能会使用compojure-api 获得此行为,您可以在其中为 URL/查询参数以及请求正文指定架构类型。 For example:

    (defapi app
      (GET "/photo/:id" []
        :path-params [id :- Long]
        (ok {:message (str "Photo with ID " id)})))
    

    通过指定[id :- Long],您要求将id 路径参数强制转换为Long 类型。

    【讨论】:

      【解决方案2】:

      从 Compojure 1.4.0 开始,您还可以使用 : 为参数提供强制函数

      [x :<< as-int]
      

      在上述情况下,参数x在被赋值之前会通过as-int函数传递。如果任何强制函数返回 nil,则认为强制失败,路由将不匹配。

      例子:

      (defroutes app 
        (GET "/customers" [] customers)
        (GET "/suppliers" [] suppliers)
        (GET "/accounts" [] accounts)
        (context "/statements" []
                 (GET "/" [] statements)
                 (GET "/:id" [id :<< as-int] (single-statement id))))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-13
        • 2023-03-28
        • 2012-10-21
        • 2016-01-22
        • 2013-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多