Clojure とMongerを使用しています
それは問題なく動作し、関連するコレクションごとに関数をグループ化します。したがって、すべてのファイルは次のように始まります。
(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」パラメーターを渡すことができると思いますが、それはどこから来るのでしょうか?
プログラムの「エントリ」ファイルに 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」のいくつかのルートから呼び出されたいくつかの関数がデータベースにアクセスする必要があるとしましょう。この変数をそれらに渡すにはどうすればよいですか?
また、その後、たとえば、すべてのコレクションの Id でデータを取得するなど、多くの反復コードがあります...これは単純化できると思いますが、方法がわかりません。