Skip to content

Commit

Permalink
fix: make inspect method for ObjectId work (#412)
Browse files Browse the repository at this point in the history
The previous Object.defineProperty() calls did not work because
they did not specify a property descriptor. 
Adds `inspect` and  inspect symbol methods directly to the ObjectId class.

NODE-2875
  • Loading branch information
addaleax authored Nov 13, 2020
1 parent 203402f commit a585a0c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 20 deletions.
24 changes: 14 additions & 10 deletions src/objectid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,20 @@ export class ObjectId {
static fromExtendedJSON(doc: ObjectIdExtended): ObjectId {
return new ObjectId(doc.$oid);
}

/**
* Converts to a string representation of this Id.
*
* @returns return the 24 character hex string representation.
* @internal
*/
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `ObjectId("${this.toHexString()}")`;
}
}

// Deprecated methods
Expand All @@ -360,14 +374,4 @@ Object.defineProperty(ObjectId, 'get_inc', {
value: deprecate(() => ObjectId.getInc(), 'Please use the static `ObjectId.getInc()` instead')
});

const inspect = Symbol.for('nodejs.util.inspect.custom');
/**
* Converts to a string representation of this Id.
*
* @returns return the 24 character hex string representation.
* @internal
*/
Object.defineProperty(ObjectId.prototype, inspect, ObjectId.prototype.toString);
Object.defineProperty(ObjectId.prototype, 'inspect', ObjectId.prototype.toString);

Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' });
11 changes: 1 addition & 10 deletions test/node/object_id_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,7 @@ describe('ObjectId', function () {
it('should correctly allow for node.js inspect to work with ObjectId', function (done) {
var a = 'AAAAAAAAAAAAAAAAAAAAAAAA';
var b = new ObjectId(a);
util.inspect(b);

// var c = b.equals(a); // => false
// expect(true).to.equal(c);
//
// var a = 'aaaaaaaaaaaaaaaaaaaaaaaa';
// var b = new ObjectId(a);
// var c = b.equals(a); // => true
// expect(true).to.equal(c);
// expect(a).to.equal(b.toString());
expect(util.inspect(b)).to.equal('ObjectId("aaaaaaaaaaaaaaaaaaaaaaaa")');

done();
});
Expand Down

0 comments on commit a585a0c

Please sign in to comment.