integrant

popeye 2023-02-09T14:05:22.942719Z

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)

Kirill Chernyshov 2023-02-09T14:13:17.820849Z

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

popeye 2023-02-09T14:29:13.011619Z

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

popeye 2023-02-09T14:29:31.145829Z

or I can define in routes

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

popeye 2023-02-09T14:29:59.897209Z

and pass the connection var in every route

Kirill Chernyshov 2023-02-09T14:33:06.481579Z

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.

popeye 2023-02-09T14:37:50.348989Z

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)))

Kirill Chernyshov 2023-02-09T14:43:02.245859Z

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.

popeye 2023-02-09T14:46:33.116559Z

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

Kirill Chernyshov 2023-02-09T14:47:17.529049Z

those are two different functions

popeye 2023-02-09T15:04:42.272529Z

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

👍 1