Reputation: 11734
I wish to make a new Pedestal interceptor to be run during the leave stage. I wish to modify the context to add a token string to the base of each html page (for use in 'site alive' reporting).
From the Pedestal source code here I see this function:
(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)}))))
So I need to provide it with a function which will then be inserted into the interceptor map. That makes sense. However, how can I write this function making reference to the context when 'context' is not in scope?
I wish to do something like:
...[io.pedestal.interceptor.helpers :as h]...
(defn my-token-interceptor []
(h/after
(fn [ctx]
(assoc ctx :response {...}))))
But 'ctx' is not in scope? Thanks.
Upvotes: 0
Views: 405
Reputation:
For what it's worth, we no longer think the before
and after
functions are the best way to do this. (All the functions in io.pedestal.interceptor.helpers
are kind of unnecessary now.)
Our recommendation is to write interceptors just as Clojure map literals, like so:
(def my-token-interceptor
{:name ::my-token-interceptor
:leave (fn [context] (assoc context :response {,,,}))})
You can see that the after
function doesn't add anything in terms of clarity or explanatory value.
Of course you can use a function value in the map rather than making an anonymous function right there:
(defn- token-function
[context]
(assoc context :response {,,,}))
(def my-token-interceptor
{:name ::my-token-interceptor
:leave token-function)})
Upvotes: 2
Reputation: 1261
the after
doc is clear on this.
(defn after
"Return an interceptor which calls `f` on context during the leave
stage."
your f
will receive context
as its first argument. You can access context
inside f
by using f
's first argument.
below is a sample of a f
function: token-function
, that will be supplied to h/after
and because h/after
returns interceptor, I create a 'my-token-interceptor' by calling h/after
with token-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`
Upvotes: 1