在 yada 中为每个路由请求添加函数

Prepend function to every route request in yada

目前我正在使用 Yada 作为 Web 库。现在我想在到达路线之前执行一些功能。

我测试过的方法: - 将当前资源包装为子资源,但 swagger-doc 找不到该资源 - 使用前置拦截器,但此时文档尚未完成,我收到错误

我的代码:

(ns all-mighty.namespace
    (:require [yada.yada :refer [handler listener resource as-resource]]
              [yada.swagger :refer [swaggered]])

(defn resources []
[""
 (swaggered
     [""
      [
       (cool-route)
       ]]
     {:info     {:title       "Hello You!"
                 :version     "1.0"
                 :description "It's something"}
      :basePath ""}
     )])

(defn cool-route []
["/cool" (resource {
                   :description "Returns somethign cool"
                   :produces    "application/json"
                   :methods     {:get {:response cool-response}}}
                  )])

(defn cool-response [ctx]
(-> (:response ctx)
    (assoc :status 200)
    (assoc :body {:state :up}))

是的,我会在后面重构资源 ;-)

有人有想法吗?

我使用的方式append-interceptor:

(ns all-mighty.namespace
  (:require
   [yada.handler :refer [append-interceptor]]
   [yada.interceptors :as i]
   [yada.swagger :refer [swaggered]]
   [yada.yada :refer [handler listener resource as-resource]]))

(defn cool-response [ctx]
  {:state :up
   :my/value (get ctx :my/value)})

(defn my-cool-interceptor [ctx]
  (assoc ctx :my/value 10))

(defn my-cool-resource
  [model]
  (-> model
   ;; you have to provide an interception chain, here we use the default one
   (assoc :interceptor-chain yada.yada/default-interceptor-chain)
   resource
   ;; here we append our interceptor after the request body has been processed
   (append-interceptor i/process-request-body my-cool-interceptor)))

(defn cool-route []
  ["/cool" (my-cool-resource {:description "Returns somethign cool"
                              :produces    "application/json"
                              :methods     {:get {:response cool-response}}})])

(defn routes []
  [""
   (swaggered
    [""
     [
      (cool-route)
      ]]
    {:info     {:title       "Hello You!"
                :version     "1.0"
                :description "It's something"}
     :basePath ""}
    )])

(comment
  (def l (listener (routes) {:port 1337}))
  ((:close l))
  )

因此,对于 /cool 下的每个资源,您都可以使用 my-cool-resource 函数自动添加所需的拦截器。