File tree Expand file tree Collapse file tree 2 files changed +24
-6
lines changed
Expand file tree Collapse file tree 2 files changed +24
-6
lines changed Original file line number Diff line number Diff line change 22var MACHINE_ID = Math . floor ( Math . random ( ) * 0xFFFFFF ) ;
33var index = ObjectID . index = parseInt ( Math . random ( ) * 0xFFFFFF , 10 ) ;
44var pid = ( typeof process === 'undefined' || typeof process . pid !== 'number' ? Math . floor ( Math . random ( ) * 100000 ) : process . pid ) % 0xFFFF ;
5+ // <https://github.com/williamkapke/bson-objectid/pull/51>
6+ // Attempt to fallback Buffer if _Buffer is undefined (e.g. for Node.js).
7+ // Worst case fallback to null and handle with null checking before using.
8+ var BufferCtr = ( ( ) => { try { return _Buffer ; } catch ( _ ) { try { return Buffer ; } catch ( _ ) { return null ; } } } ) ( ) ;
59
610/**
711 * Determine if an object is Buffer
@@ -144,16 +148,20 @@ ObjectID.isValid = function(id) {
144148 return true ;
145149 }
146150
151+ // <https://github.com/williamkapke/bson-objectid/issues/53>
147152 if ( isBuffer ( id ) ) {
148- return true ;
153+ return ObjectID . isValid ( id . toString ( 'hex' ) ) ;
149154 }
150155
151156 // Duck-Typing detection of ObjectId like objects
152- if (
153- typeof id . toHexString === 'function' &&
154- ( id . id instanceof _Buffer || typeof id . id === 'string' )
155- ) {
156- return id . id . length === 12 || ( id . id . length === 24 && checkForHexRegExp . test ( id . id ) ) ;
157+ // <https://github.com/williamkapke/bson-objectid/pull/51>
158+ if ( typeof id . toHexString === 'function' ) {
159+ if (
160+ BufferCtr &&
161+ ( id . id instanceof BufferCtr || typeof id . id === 'string' )
162+ ) {
163+ return id . id . length === 12 || ( id . id . length === 24 && checkForHexRegExp . test ( id . id ) ) ;
164+ }
157165 }
158166
159167 return false ;
Original file line number Diff line number Diff line change @@ -30,6 +30,11 @@ describe("ObjectIDs", function() {
3030 o . toHexString ( ) . should . eql ( "54495ad94c934721ede76d90" ) ;
3131 } ) ;
3232
33+ it ( "should not be valid with invalid buffer" , function ( ) {
34+ var buffer = Buffer . from ( 'hello' ) ;
35+ ObjectID . isValid ( buffer ) . should . not . be . ok ;
36+ } ) ;
37+
3338 it ( "should construct with a `hexString` argument" , function ( ) {
3439 var hexString = "54495ad94c934721ede76d90" ;
3540 var o = new ObjectID ( hexString ) ;
@@ -129,4 +134,9 @@ describe("ObjectIDs", function() {
129134 obj . toString . should . not . be . ok ;
130135 ObjectID . isValid ( obj ) . should . not . be . ok ;
131136 } ) ;
137+
138+ it ( "should use Buffer when _Buffer is undefined" , function ( ) {
139+ var obj = { id : Buffer . from ( "54495ad94c934721ede76d90" ) , toHexString : ( ) => "" } ;
140+ ObjectID . isValid ( obj ) . should . be . true ;
141+ } ) ;
132142} ) ;
You can’t perform that action at this time.
0 commit comments