From 13d75b7f7ea2a0f6e85b7122bb8306c2fa56d0f3 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Thu, 5 Nov 2020 18:01:12 +0100 Subject: [PATCH] fix: make inspect for ObjectId work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous `Object.defineProperty()` calls did not work because they did not specify a property descriptor, and even if they had worked, the signatures of `.inspect()` and `.toString()` would have mismatched, and even if they weren’t, the result would not have been very useful as debugging output, because it only returned the raw hex content of the `ObjectId` and not even e.g. the fact that this object is an `ObjectId`. I’m happy with any other solution, but this particular one would make my life a tiny bit easier :) --- src/objectid.ts | 24 ++++++++++++++---------- test/node/object_id_tests.js | 11 +---------- 2 files changed, 15 insertions(+), 20 deletions(-) diff --git a/src/objectid.ts b/src/objectid.ts index 53040215..9dbb65cd 100644 --- a/src/objectid.ts +++ b/src/objectid.ts @@ -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 @@ -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' }); diff --git a/test/node/object_id_tests.js b/test/node/object_id_tests.js index beb3bceb..6dff5afd 100644 --- a/test/node/object_id_tests.js +++ b/test/node/object_id_tests.js @@ -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(); });