【问题标题】:Clojure - avoid duplicated code with monger requestsClojure - 避免重复代码与 monger 请求
【发布时间】:2015-07-03 22:01:40
【问题描述】:

我正在使用 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”参数,但是它来自哪里?

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

例如,假设我在不同的文件中有 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 获取每个集合的数据... 我觉得这可以简化,但我不确定如何。

【问题讨论】:

    标签: clojure monger


    【解决方案1】:

    只需通过它的命名空间来引用它

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

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多