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獲取數據...我覺得這可以簡化,但我不知道如何。