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.
(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
@ -36,11 +36,16 @@
`(binding [*ns* (the-ns ~ns)]
~@(map (fn [form] `(eval '~form)) body)))
(defprotocol GetDBObjectId
(get-id [input] "Returns object id"))
(defprotocol GetDocumentId
(get-id [input] "Returns document id"))
(extend-protocol GetDBObjectId
(extend-protocol GetDocumentId
DBObject
(get-id
[^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
(let [id ^ObjectId (monger.util/object-id)
input ^DBObject (monger.conversion/to-db-object { :_id id })
output (monger.util/get-id input)]
(is (not (nil? output)))))
(let [clj-map { :_id (monger.util/object-id) }
db-object ^DBObject (monger.conversion/to-db-object clj-map)
_id (:_id clj-map)]
(is (= _id (monger.util/get-id clj-map)))
(is (= _id (monger.util/get-id db-object)))))