forked from helpshift/mongrove
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conversion.clj
111 lines (85 loc) · 2.31 KB
/
conversion.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
(ns mongrove.conversion
(:import
(clojure.lang
IPersistentMap
Keyword
Named
Ratio)
(com.mongodb
BasicDBList
DBObject
DBRef)
(java.util
Date
List
Map
Set)
org.bson.Document
(org.bson.types
Decimal128)))
(defprotocol ConvertToBsonDocument
(^org.bson.Document to-bson-document
[input]
"Converts given piece of Clojure data to BasicDBObject MongoDB Java driver uses"))
(extend-protocol ConvertToBsonDocument
nil
(to-bson-document [input]
nil)
String
(to-bson-document [^String input]
input)
Boolean
(to-bson-document [^Boolean input]
input)
java.util.Date
(to-bson-document [^java.util.Date input]
input)
Ratio
(to-bson-document [^Ratio input]
(double input))
Keyword
(to-bson-document [^Keyword input] (.getName input))
Named
(to-bson-document [^Named input] (.getName input))
IPersistentMap
(to-bson-document [^IPersistentMap input]
(let [o (Document.)]
(doseq [[k v] input]
(.append o (to-bson-document k) (to-bson-document v)))
o))
List
(to-bson-document [^List input] (map to-bson-document input))
Set
(to-bson-document [^Set input] (map to-bson-document input))
Object
(to-bson-document [input]
input))
(defprotocol ConvertFromBsonDocument
(from-bson-document
[input keywordize]
"Converts given DBObject instance to a piece of Clojure data"))
(extend-protocol ConvertFromBsonDocument
nil
(from-bson-document [input keywordize] input)
Object
(from-bson-document [input keywordize] input)
Decimal128
(from-bson-document [^Decimal128 input keywordize]
(.bigDecimalValue input))
List
(from-bson-document [^List input keywordize]
(vec (map #(from-bson-document % keywordize) input)))
BasicDBList
(from-bson-document [^BasicDBList input keywordize]
(vec (map #(from-bson-document % keywordize) input)))
DBRef
(from-bson-document [^DBRef input keywordize]
input)
Document
(from-bson-document [^Document input keywordize]
(reduce (if keywordize
(fn [m ^String k]
(assoc m (keyword k) (from-bson-document (.get input k) true)))
(fn [m ^String k]
(assoc m k (from-bson-document (.get input k) false))))
{} (.keySet input))))