monger.util/get-id now can also handle Clojure maps, using both :_id and "_id" as id keys

This commit is contained in:
Michael S. Klishin 2011-09-11 23:16:36 +04:00
parent 09a19c67eb
commit 57d8e62058
2 changed files with 15 additions and 9 deletions

View file

@ -8,7 +8,7 @@
;; You must not remove this notice, or any other, from this software. ;; You must not remove this notice, or any other, from this software.
(ns monger.util (ns monger.util
(:import (java.security SecureRandom) (java.math BigInteger) (org.bson.types ObjectId) (com.mongodb DBObject))) (:import (java.security SecureRandom) (java.math BigInteger) (org.bson.types ObjectId) (com.mongodb DBObject) (clojure.lang IPersistentMap) (java.util Map)))
;; ;;
;; API ;; API
@ -36,11 +36,16 @@
`(binding [*ns* (the-ns ~ns)] `(binding [*ns* (the-ns ~ns)]
~@(map (fn [form] `(eval '~form)) body))) ~@(map (fn [form] `(eval '~form)) body)))
(defprotocol GetDBObjectId (defprotocol GetDocumentId
(get-id [input] "Returns object id")) (get-id [input] "Returns document id"))
(extend-protocol GetDBObjectId (extend-protocol GetDocumentId
DBObject DBObject
(get-id (get-id
[^DBObject object] [^DBObject object]
(.get ^DBObject object "_id"))) (.get object "_id"))
IPersistentMap
(get-id
[^IPersistentMap object]
(or (:_id object) ("_id" object))))

View file

@ -5,9 +5,10 @@
(deftest get-object-id (deftest get-object-id
(let [id ^ObjectId (monger.util/object-id) (let [clj-map { :_id (monger.util/object-id) }
input ^DBObject (monger.conversion/to-db-object { :_id id }) db-object ^DBObject (monger.conversion/to-db-object clj-map)
output (monger.util/get-id input)] _id (:_id clj-map)]
(is (not (nil? output))))) (is (= _id (monger.util/get-id clj-map)))
(is (= _id (monger.util/get-id db-object)))))