我正在使用Clojure和商人
它工作得很好,我根据与它们相关的集合对函数进行分组。因此,每个文件的开头都是这样的:
(ns img-cli.model.mycollectionname
(:require [monger.core :as mg]
[monger.collection :as mc]
[edn-config.core :refer [env]])
(:import [com.mongodb MongoOptions ServerAddress DB WriteConcern]
[org.bson.types ObjectId]))
(def config (get-in env [:mongo]))
;; using MongoOptions allows fine-tuning connection parameters,
;; like automatic reconnection (highly recommended for production
;; environment)
(def ^MongoOptions opts (mg/mongo-options { :threads-allowed-to-block-for-connection-multiplier 300}))
(def ^ServerAddress sa (mg/server-address (:url config) (:port config)))
(def conn (mg/connect sa opts))
(def db (mg/get-db conn (:db config)))
(def collection-name "asset")
;; I have to write one like this every time
(defn find-one-as-map
"fetch asset by Id"
[^String id]
(mc/find-one-as-map db collection-name {:_id (ObjectId. id)}))当然,代码复制本身也有几个缺点。另外,我也不确定连接之后是否正确地进行了池化?
我怎么才能避免这样做呢?我感觉到我可以向每个函数传递一个额外的"db“参数,但是它从何而来呢?
如果我在我的程序的"entry“文件中创建了db连接,那么如何从那里将它传递给每个函数?
例如,假设我在不同的文件中有Compojure路由:
;; in the main handler file
(def db ...) ;; if I move the previous db configuration
;; in here, it could be the only place where this is set
;; importing Compojure routes from different files
(defroutes routes-from-file1
routes-from-file2...)假设从"file2“中的某些路由调用的一些函数需要访问db,那么如何将这个变量传递给它们呢?
之后我还有很多重复的代码,例如,通过Id获取每个集合的数据.我觉得这可以简化,但我不知道怎么做。
发布于 2015-07-03 14:01:40
只需按其命名空间引用它即可。
(ns foo
(:require [handler :as h]))
(println h/db)https://stackoverflow.com/questions/31208542
复制相似问题