Fork me on GitHub
#integrant
<
2023-02-09
>
popeye14:02:22

I have configured db using below code, Is there a way where I can have single connection var in integrant ?

(defmethod ig/init-key :db/postgres
  [_ config]
  (println "\n Configured DB")
  (:jdbc-url config))

(defn -main
  []
  (let [system (ig/init a/config)])
  system)

delaguardo14:02:17

init-key should return either a connection pool or connection. in your example it returns just db url.

popeye14:02:13

@U04V4KLKC where should I define a connection object? during startup ?

popeye14:02:31

or I can define in routes

(defn routes
  [env]
  [["/"
     {:get {:handler (fn [req]
                       {:status 200
                        :body "Hello Apple"})}}]
   ["/v1"
    (recipe/routes env)]])

popeye14:02:59

and pass the connection var in every route

delaguardo14:02:06

database has nothing to do with routes

(defmethod ig/init-key :db/postgres
  [_ config]
  (println "\n Configured DB")
  (create-connection-pool (:jdbc-url config)))

(defmethod ig/halt-key! :db/postgres [_ db]
  (.close db))
create-connection-pool should be a function that takes jdbc-url and creates connection pool. Then you can include the key :db/postgres into system config and after you start you application the reference to this key in any other component will have a real connection pool.

popeye14:02:50

we need to store connection in some var right, to make use it in other namespace. So should I do it as code below? or we have any other way

(def conn (atom {}))

(defn create-connection-pool [jdbc-config]
  (with-open [conn-system (jdbc/get-connection jdbc-config)]
    (reset! conn conn-system)))

delaguardo14:02:02

no, if you are using integrant than it would be better to start using it how it suppose to.

(defmethod ig/init-key :db/postgres
  [_ config]
  (println "\n Configured DB")
  (create-connection-pool (:jdbc-url config)))

(defmethod ig/halt-key! :db/postgres [_ db]
  (.close db))

(defmethod ig/init-key :services/handler [_ {:keys [db]}]
  (start-service db))

(def config
  {:db/postgres {:jdbc-url "jdbc:postgres://..."}
   :services/handler {:db (ig/ref :db/postgres)}})

(defn -main [& args]
  (ig/init config))
:services/handler can be defined in any namespace but it will always have access to the connection pool through db reference.

popeye14:02:33

what is the difference between start-service and create-connection here >?

delaguardo14:02:17

those are two different functions

popeye15:02:42

I understood that and developed in same way! Thank you 🙂

👍 2