Skip to content

Commit ed748e1

Browse files
author
Grace Chong
committed
refactor: validate that id satisfies the ObjectIdLike type def of id and add test for invalid id type
1 parent fd0a5a4 commit ed748e1

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/objectid.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,14 @@ export class ObjectId {
5656
if (typeof id === 'object' && id && 'id' in id) {
5757
if ('toHexString' in id && typeof id.toHexString === 'function') {
5858
this[kId] = Buffer.from(id.toHexString(), 'hex');
59+
} else if (typeof id.id === 'string') {
60+
this[kId] = Buffer.from(id.id);
5961
} else {
60-
this[kId] = typeof id.id === 'string' ? Buffer.from(id.id) : id.id;
62+
try {
63+
this[kId] = ensureBuffer(id.id);
64+
} catch {
65+
throw new BSONTypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters');
66+
}
6167
}
6268
} else if (id == null || typeof id === 'number') {
6369
// The most common use case (blank id, new objectId instance)

test/node/object_id_tests.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,14 @@ describe('ObjectId', function () {
4848
expect(() => new ObjectId(objectIdLike)).to.throw(TypeError);
4949
});
5050

51+
it('should throw error if object without string or buffer id is passed in', function () {
52+
var objectIdLike = {
53+
id: 5
54+
};
55+
56+
expect(() => new ObjectId(objectIdLike)).to.throw(TypeError);
57+
});
58+
5159
it('should correctly create ObjectId from number', function () {
5260
expect(() => new ObjectId(42)).to.not.throw();
5361
expect(() => new ObjectId(0x2a)).to.not.throw();

0 commit comments

Comments
 (0)