Skip to content

Commit 71963d3

Browse files
some fixes...
Signed-off-by: Aayush Chouhan <achouhan@redhat.com>
1 parent e905934 commit 71963d3

File tree

2 files changed

+26
-13
lines changed

2 files changed

+26
-13
lines changed

src/sdk/nb.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ interface Base {
4747
toString?(): string;
4848
}
4949

50-
type ID = string;
50+
type ID = mongo_utils.ObjectId;
5151
type DBBuffer = mongodb.Binary | Buffer;
5252

5353
interface System extends Base {

src/util/mongo_utils.js

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -158,10 +158,29 @@
158158
// return doc;
159159
// }
160160

161-
function is_object_id(id) {
162-
return typeof id === 'string' && (/^[0-9a-f]{24}$/i).test(id);
161+
function is_object_id(id, generate = false) {
162+
const ERROR_MSG = 'Argument passed must be a single string of 12 bytes or a string of 24 hex characters';
163+
164+
if (id === null || id === undefined) {
165+
return generate ? mongoObjectId() : false;
166+
}
167+
168+
let hex_string = null;
169+
if (typeof id === 'string') {
170+
hex_string = id;
171+
} else if (id._id && typeof id._id === 'string') {
172+
hex_string = id._id;
173+
}
174+
175+
if (hex_string && (/^[0-9a-f]{24}$/i).test(hex_string)) {
176+
return generate ? hex_string.toLowerCase() : true;
177+
}
178+
179+
if (generate) throw new Error(ERROR_MSG);
180+
return false;
163181
}
164182

183+
165184
function mongoObjectId() {
166185
// eslint-disable-next-line no-bitwise
167186
const timestamp = (new Date().getTime() / 1000 | 0).toString(16);
@@ -232,15 +251,11 @@ function mongoObjectId() {
232251

233252
/**
234253
* MongoDB ObjectId compatibility class
235-
* Behaves like mongodb.ObjectId but returns strings
254+
* behaves like mongodb.ObjectId with minimal validations
236255
*/
237256
class ObjectID {
238257
constructor(id_str) {
239-
if (id_str === undefined || id_str === null) {
240-
this._id = mongoObjectId();
241-
} else {
242-
this._id = String(id_str);
243-
}
258+
this._id = is_object_id(id_str, true);
244259
}
245260

246261
toString() {
@@ -252,17 +267,15 @@ class ObjectID {
252267
}
253268

254269
valueOf() {
255-
return this._id;
270+
return this;
256271
}
257272

258273
toJSON() {
259274
return this._id;
260275
}
261276

262277
getTimestamp() {
263-
// Extract timestamp from first 4 bytes of ObjectId hex string
264-
const timestampHex = this._id.substring(0, 8);
265-
const timestamp = parseInt(timestampHex, 16);
278+
const timestamp = parseInt(this._id.substring(0, 8), 16);
266279
return new Date(timestamp * 1000);
267280
}
268281

0 commit comments

Comments
 (0)