2

我正在尝试设置一个执行强制的 Reitit 路由器。我可以让响应部分正常工作,但我似乎无法让身体强制正常工作。以下是我正在使用的代码:

(ns example
  (:require
   [ring.middleware.json :refer [wrap-json-body wrap-json-response]]
   [ring.middleware.reload :refer [wrap-reload]]
   [ring.util.response :refer [response]]
   [reitit.ring.coercion :as rrc]
   [reitit.coercion.malli]
   [reitit.ring :as ring]))

(def router
  (ring/ring-handler
   (ring/router
    [["/healthz" {:get (fn [_] {:status 200 :body "healthy"})}]
     ["/api" {:coercion reitit.coercion.malli/coercion
              :middleware [rrc/coerce-exceptions-middleware
                           rrc/coerce-request-middleware
                           rrc/coerce-response-middleware]}
      ["/messages" {:post {:summary "Add a new message"
                           :parameters {:body [:map [:name string?]]}
                           :responses {200 {:body [:map
                                                   [:message string?]]}}
                           :handler (fn [req]
                                      {:status 200 :body {:message (:name (:body req))}})}}]]]
    {:data {:middleware []}})
   (ring/create-default-handler)))

(def app (-> #'router
             (wrap-reload)
             (wrap-json-response)
             (wrap-json-body {:keywords? true :bigdecimals? true})))

即使我发送正确的正文参数并出现以下错误,强制也会失败:

{
  "schema": "[:map {:closed true} [:name string?]]",
  "errors": [
    {
      "path": [],
      "in": [],
      "schema": "[:map {:closed true} [:name string?]]",
      "value": null,
      "type": "malli.core/invalid-type",
      "message": "invalid type"
    }
  ],
  "value": null,
  "type": "reitit.coercion/request-coercion",
  "coercion": "malli",
  "in": [
    "request",
    "body-params"
  ],
  "humanized": [
    "invalid type"
  ]
}

这似乎表明强制无法找到任何身体参数。我认为这与我设置中间件的方式有关,但我似乎无法解决这个问题。我应该如何设置中间件,以便 Reitit 强制在这种情况下正常工作?

4

1 回答 1

8

通过删除 wrap-json-response 和 wrap-json-body 中间件并将其替换为 muuntaja 中间件,我能够强制工作,如下所示:

(def router
  (ring/ring-handler
   (ring/router
    [["/healthz" {:get (fn [_] {:status 200 :body "healthy"})}]
     ["/api" {:coercion reitit.coercion.malli/coercion
              :middleware []}
      ["/messages" {:name ::message
                    :post {:summary "Add a new message"
                           :parameters {:body [:map [:name string?]]}
                           :responses {200 {:body [:map
                                                   [:message string?]]}}
                           :handler (fn [{:keys [parameters]}]
                                      {:status 200 :body {:message (:name (:body parameters))}})}}]]]
    {:data {:muuntaja m/instance
            :middleware [params/wrap-params
                         muuntaja/format-middleware
                         rrc/coerce-exceptions-middleware
                         rrc/coerce-request-middleware
                         rrc/coerce-response-middleware]}})
   (ring/create-default-handler)))
于 2020-03-07T08:49:33.013 回答