0

我希望制作一个新的 Pedestal 拦截器,以便在离开阶段运行。我希望修改上下文以将令牌字符串添加到每个 html 页面的底部(用于“站点活动”报告)。

这里的基座源代码中,我看到了这个函数:

(defn after
 "Return an interceptor which calls `f` on context during the leave
 stage."
 ([f] (interceptor {:leave f}))
 ([f & args]
    (let [[n f args] (if (fn? f)
                    [nil f args]
                    [f (first args) (rest args)])]
      (interceptor {:name (interceptor-name n)
                 :leave #(apply f % args)}))))

所以我需要为它提供一个函数,然后将其插入拦截器映射中。那讲得通。但是,当“上下文”不在范围内时,如何编写引用上下文的函数?

我想做类似的事情:

...[io.pedestal.interceptor.helpers :as h]...

(defn my-token-interceptor []
  (h/after
    (fn [ctx]
      (assoc ctx :response {...}))))

但是'ctx'不在范围内?谢谢。

4

2 回答 2

1

对于它的价值,我们不再认为beforeandafter函数是最好的方法。(现在所有的功能io.pedestal.interceptor.helpers都没有必要了。)

我们的建议是像 Clojure 映射文字一样编写拦截器,如下所示:

(def my-token-interceptor
  {:name ::my-token-interceptor
   :leave (fn [context] (assoc context :response {,,,}))})

您可以看到该after函数在清晰度或解释性方面没有添加任何内容。

当然,您可以在映射中使用函数值,而不是在此处创建匿名函数:

(defn- token-function
  [context]
  (assoc context :response {,,,}))

(def my-token-interceptor
  {:name  ::my-token-interceptor
   :leave token-function)})
于 2016-11-19T18:18:55.413 回答
1

文档对此after很清楚。

(defn after
 "Return an interceptor which calls `f` on context during the leave
 stage."

f将收到context作为它的第一个参数。您可以使用的第一个参数访问context内部。ff

下面是一个f函数示例:token-function,它将提供给h/after并且因为返回拦截器,我通过调用创建h/after一个“my-token-interceptor”h/aftertoken-function

...[io.pedestal.interceptor.helpers :as h]...

(defn token-function
  ""
  [ctx]
  (assoc ctx :response {}))

(def my-token-interceptor (h/after token-function))

;; inside above token-function, ctx is pedestal `context`
于 2016-06-16T09:55:55.147 回答