diff --git a/objectid.js b/objectid.js index 1112244..3e9f8b8 100644 --- a/objectid.js +++ b/objectid.js @@ -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; +// +// 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 @@ -144,16 +148,20 @@ ObjectID.isValid = function(id) { return true; } + // 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)); + // + 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; diff --git a/test/test.js b/test/test.js index 01ef87c..3ec6720 100644 --- a/test/test.js +++ b/test/test.js @@ -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); @@ -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; + }); });