Skip to content

Commit

Permalink
feat: fixed buffer and _Buffer issues (closes #50) (closes #51)
Browse files Browse the repository at this point in the history
  • Loading branch information
titanism committed Nov 21, 2022
1 parent 68c4539 commit c948134
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
20 changes: 14 additions & 6 deletions objectid.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
var MACHINE_ID = Math.floor(Math.random() * 0xFFFFFF);
var index = ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10);
var pid = (typeof process === 'undefined' || typeof process.pid !== 'number' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF;
// <https://github.com/williamkapke/bson-objectid/pull/51>
// Attempt to fallback Buffer if _Buffer is undefined (e.g. for Node.js).
// Worst case fallback to null and handle with null checking before using.
var BufferCtr = (() => { try { return _Buffer; }catch(_){ try{ return Buffer; }catch(_){ return null; } } })();

/**
* Determine if an object is Buffer
Expand Down Expand Up @@ -144,16 +148,20 @@ ObjectID.isValid = function(id) {
return true;
}

// <https://github.com/williamkapke/bson-objectid/issues/53>
if (isBuffer(id)) {
return true;
return ObjectID.isValid(id.toString('hex'));
}

// Duck-Typing detection of ObjectId like objects
if (
typeof id.toHexString === 'function' &&
(id.id instanceof _Buffer || typeof id.id === 'string')
) {
return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id));
// <https://github.com/williamkapke/bson-objectid/pull/51>
if (typeof id.toHexString === 'function') {
if(
BufferCtr &&
(id.id instanceof BufferCtr || typeof id.id === 'string')
) {
return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id));
}
}

return false;
Expand Down
10 changes: 10 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ describe("ObjectIDs", function() {
o.toHexString().should.eql("54495ad94c934721ede76d90");
});

it("should not be valid with invalid buffer", function() {
var buffer = Buffer.from('hello');
ObjectID.isValid(buffer).should.not.be.ok;
});

it("should construct with a `hexString` argument", function() {
var hexString = "54495ad94c934721ede76d90";
var o = new ObjectID(hexString);
Expand Down Expand Up @@ -129,4 +134,9 @@ describe("ObjectIDs", function() {
obj.toString.should.not.be.ok;
ObjectID.isValid(obj).should.not.be.ok;
});

it("should use Buffer when _Buffer is undefined", function() {
var obj = { id: Buffer.from("54495ad94c934721ede76d90"), toHexString: () => "" };
ObjectID.isValid(obj).should.be.true;
});
});

0 comments on commit c948134

Please sign in to comment.