Skip to content

Commit cb50091

Browse files
committed
fix: ObjectId() retuns an _id string, ObjectId(some_id) will validate and thorw an error if not valid
1 parent 5e6519b commit cb50091

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/index.js

+16-2
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,22 @@
3939

4040
}
4141

42-
const ObjectId = (rnd = r16 => Math.floor(r16).toString(16)) =>
43-
rnd(Date.now() / 1000) + ' '.repeat(16).replace(/./g, () => rnd(Math.random() * 16));
42+
const ObjectId = (id) => {
43+
// Define the rnd function
44+
const rnd = (r16) => Math.floor(r16).toString(16);
45+
46+
if (id === undefined) {
47+
// If id is undefined, generate a new ObjectId
48+
return rnd(Date.now() / 1000) + '0'.repeat(16).replace(/./g, () => rnd(Math.random() * 16));
49+
} else {
50+
// Check if the provided id is a valid ObjectId
51+
const validIdRegex = /^[0-9a-fA-F]{24}$/;
52+
if (!validIdRegex.test(id)) {
53+
throw new Error('Invalid ObjectId');
54+
}
55+
return id; // Return the valid ObjectId as a string
56+
}
57+
};
4458

4559
function checkValue(value) {
4660
if (/{{\s*([\w\W]+)\s*}}/g.test(value))

0 commit comments

Comments
 (0)