clojurepedestal

How to use 'after' function to create interceptor in Pedestal


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.


Solution

  • 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`