forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathid.js
95 lines (82 loc) · 2.63 KB
/
id.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
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
MongoID = {};
MongoID._looksLikeObjectID = function (str) {
return str.length === 24 && str.match(/^[0-9a-f]*$/);
};
MongoID.ObjectID = function (hexString) {
//random-based impl of Mongo ObjectID
var self = this;
if (hexString) {
hexString = hexString.toLowerCase();
if (!MongoID._looksLikeObjectID(hexString)) {
throw new Error("Invalid hexadecimal string for creating an ObjectID");
}
// meant to work with _.isEqual(), which relies on structural equality
self._str = hexString;
} else {
self._str = Random.hexString(24);
}
};
MongoID.ObjectID.prototype.toString = function () {
var self = this;
return "ObjectID(\"" + self._str + "\")";
};
MongoID.ObjectID.prototype.equals = function (other) {
var self = this;
return other instanceof MongoID.ObjectID &&
self.valueOf() === other.valueOf();
};
MongoID.ObjectID.prototype.clone = function () {
var self = this;
return new MongoID.ObjectID(self._str);
};
MongoID.ObjectID.prototype.typeName = function() {
return "oid";
};
MongoID.ObjectID.prototype.getTimestamp = function() {
var self = this;
return parseInt(self._str.substr(0, 8), 16);
};
MongoID.ObjectID.prototype.valueOf =
MongoID.ObjectID.prototype.toJSONValue =
MongoID.ObjectID.prototype.toHexString =
function () { return this._str; };
EJSON.addType("oid", function (str) {
return new MongoID.ObjectID(str);
});
MongoID.idStringify = function (id) {
if (id instanceof MongoID.ObjectID) {
return id.valueOf();
} else if (typeof id === 'string') {
if (id === "") {
return id;
} else if (id.substr(0, 1) === "-" || // escape previously dashed strings
id.substr(0, 1) === "~" || // escape escaped numbers, true, false
MongoID._looksLikeObjectID(id) || // escape object-id-form strings
id.substr(0, 1) === '{') { // escape object-form strings, for maybe implementing later
return "-" + id;
} else {
return id; // other strings go through unchanged.
}
} else if (id === undefined) {
return '-';
} else if (typeof id === 'object' && id !== null) {
throw new Error("Meteor does not currently support objects other than ObjectID as ids");
} else { // Numbers, true, false, null
return "~" + JSON.stringify(id);
}
};
MongoID.idParse = function (id) {
if (id === "") {
return id;
} else if (id === '-') {
return undefined;
} else if (id.substr(0, 1) === '-') {
return id.substr(1);
} else if (id.substr(0, 1) === '~') {
return JSON.parse(id.substr(1));
} else if (MongoID._looksLikeObjectID(id)) {
return new MongoID.ObjectID(id);
} else {
return id;
}
};