forked from stemey/mongomat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathejsonHelper.js
59 lines (49 loc) · 1.05 KB
/
ejsonHelper.js
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
var EJSON = require('mongodb-extended-json');
var EjsonHelper = function () {
}
/**
* transform native js object to serializable ejson
* @param doc
* @returns {*}
*/
EjsonHelper.prototype.inflate = function (doc) {
var id=doc._id;
var newDoc = EJSON.inflate(doc);
newDoc._id=this.inflateId(id);
return newDoc;
}
EjsonHelper.prototype.inflateId = function (id) {
var id = EJSON.inflate(id);
if (typeof id == "object") {
return "oid(" + id.$oid + ")";
}else{
return id;
}
}
EjsonHelper.prototype.inflateArray = function (doc) {
return doc.map(function (el) {
return this.inflate(el);
}, this);
}
EjsonHelper.prototype.deflateId = function (id) {
if (typeof id == "string") {
var parts = id.match(/oid\((.*)\)/);
if (parts) {
return EJSON.deflate({$oid: parts[1]});
} else {
return id;
}
} else {
return id;
}
}
/**
* transform ejson to native js
* @param doc
* @returns {*}
*/
EjsonHelper.prototype.deflate = function (doc) {
doc._id = this.deflateId(doc._id);
return EJSON.deflate(doc);
}
module.exports = new EjsonHelper();;