pedestal 2024-10-12

Valentín Fernández 2024-10-12T19:50:56.803929Z

Hi, I'm injecting to every context map, the DB connection:

(defmethod ig/init-key :app/server [_ {:keys [port routes db]}]
  (println "Server running on port" port)
  (-> {::http/routes routes
       ::http/type :jetty
       ::http/join? false 
       ::http/port port}
      (http/default-interceptors)
      (update ::http/interceptors concat [(inject-database db) validate-schema content-negotiation])
      (http/create-server)
      (http/start)))
Through the inject-database interceptor:
(defn inject-database [db]
  (interceptor/interceptor
   {:name ::inject-database
    :enter (fn [context]
             (assoc context :db db))}))
This is my handler response function:
(defn get-users
  [{:keys [db] :as context}]
  (assoc context :response (ok (db 'get-users))))
With that code I got the following error: "java.lang.NullPointerException: Cannot invoke "clojure.lang.IFn.invoke(Object)" because "db" is null". But if i write my handler response as a Interceptor works well:
(def get-users
  {:name :get-users
   :enter
   (fn [{:keys [db] :as context}]
     (assoc context :response (ok (db 'get-users))))})
Why I have to write my handler response as a interceptor to make it works?

Terminal “handlers” (not interceptors) get the value of the :request key in the interceptor context and are expected to return a value for the :response key

Valentín Fernández 2024-10-12T19:59:07.757189Z

So if I need to take the db connection from the context map, the only wey is to write an interceptor?

(or put the connection in the request)

e.g.

(defn inject-database [db]
  (interceptor/interceptor
   {:name ::inject-database
    :enter (fn [context]
             (assoc-in context [:request :db] db))}))

Valentín Fernández 2024-10-12T20:06:30.102859Z

Ooh I got it! Thanks, I really appreciate your answer

you're most welcome