How to use interceptors to read from header?

I just want to try out how interceptors and headers work. So let’s say there’s one interceptor that will attach something to the headers and another interceptor that will read from that header. So how to do this? Thank you.

As a bipedal primate, when I hear the words “interceptor” and “header” in the same sentence my first thoughts are “web server!” and “maybe Pedestal!”

Is that what you’re asking about?

I reckon it’s a pretty common pattern in web servers because we separate concerns among interceptors. We may have 1 interceptor that notices the request asks for a gif and assoc’s to the context a response with the gif’s byte array. We may have another interceptor that inspects all responses “on the way out” and assoc’s a Cache-Control header. But it does not want to obliterate a Cache-Control that’s already there.

Interceptors are essentially just a flow-control mechanism, so there is no special case for a second interceptor’s “revising” things another interceptor stuck into the context map, vs two parts of the same function repeatedly updating a map.

Hey phil, it involves Pedestal. I did it like this:

     (ns com.app.graphql.server
      (:require [integrant.core :as ig]
                [io.pedestal.http :as http]
                [com.walmartlabs.lacinia.pedestal2 :as lp2]
                [com.walmartlabs.lacinia.pedestal :as lp]))
      
    (def modify-headers
      {:name  ::modify-headers
       :enter (fn [context]
                (assoc-in context [:request :headers :some-key] :some-val))})

    (def read-headers
      {:name  ::read-headers
       :enter (fn [context]
                (let [val (get-in context [:request :headers :some-key]))]
                  (println val)
                  context)})

    (defn- inject-interceptors [interceptors]
      (-> (lp/inject interceptors modify-headers :before ::lp/inject-app-context)
          (lp/inject read-headers :after ::modify-headers))


    (defn- interceptors [schema]
      (let [options {}
            default-interceptors (lp/default-interceptors schema options)]
        (inject-interceptors default-interceptors)))

    (defmethod ig/init-key :com.app.graphql/server [_ {schema :schema}]
      (let [options (conj {:interceptors (interceptors schema)})]
         (-> schema
            (lp2/default-service options)
           http/create-server
            http/start)))

    (defmethod ig/halt-key! :com.app.graphql/server [_ server]
    (http/stop server))

But now it’s a graphql app, when I run the server all I can get is the graphiql ide, where I can run the queries, mutations and subscriptions but how can I test this interceptor? Thank you.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.