2015-07-03 39 views
0

我使用的Clojure和Monger的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”参数给每个函数,但是它会从哪里来?

如果我在我的程序的“入口”文件中创建数据库连接,那么它怎么能从那里传递给每个函数呢?

例如,让我们说,我已经在不同的文件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...) 

比方说,有些功能在“文件2”从一些路线的所谓需要访问数据库,我怎么可以通过这个变量给他们 ?

之后我也有很多重复的代码,例如通过每个集合的Id获取数据...我觉得这可以简化,但我不知道如何。

回答

0

只是指它通过其命名空间

(ns foo 
    (:require [handler :as h])) 
(println h/db)