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)init-key should return either a connection pool or connection. in your example it returns just db url.
@delaguardo where should I define a connection object? during startup ?
or I can define in routes
(defn routes
[env]
[["/"
{:get {:handler (fn [req]
{:status 200
:body "Hello Apple"})}}]
["/v1"
(recipe/routes env)]])and pass the connection var in every route
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.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)))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.what is the difference between start-service and create-connection here >?
those are two different functions
I understood that and developed in same way! Thank you 🙂