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
So if I need to take the db connection from the context map, the only wey is to write an interceptor?
Yes
(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))}))Ooh I got it! Thanks, I really appreciate your answer
you're most welcome