Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions packages/shell-api/src/shell-bson.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,13 +391,10 @@ describe('Shell BSON', () => {
expect(shellBson.UUID('01234567-89ab-cdef-0123-456789abcdef').value())
.to.equal(shellBson.UUID('0123456789abcdef0123456789abcdef').value());
});
it('errors for missing arg 1', () => {
try {
(shellBson.UUID as any)();
} catch (e) {
return expect(e.message).to.contain('Missing required argument');
}
expect.fail('Expecting error, nothing thrown');
it('generates a random UUID when no arguments are passed', () => {
// https://en.wikipedia.org/wiki/Universally_unique_identifier#Format
expect(shellBson.UUID().value(true).toString('hex')).to.match(
/^[a-z0-9]{12}4[a-z0-9]{3}[89ab][a-z0-9]{15}$/);
});
it('errors for wrong type of arg 1', () => {
try {
Expand Down
13 changes: 10 additions & 3 deletions packages/shell-api/src/shell-bson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Help from './help';
import { BinaryType, bson as BSON } from '@mongosh/service-provider-core';
import { CommonErrors, MongoshInternalError, MongoshInvalidInputError } from '@mongosh/errors';
import { assertArgsDefined, assertArgsType } from './helpers';
import { randomBytes } from 'crypto';

function constructHelp(className: string): Help {
const classHelpKeyPrefix = `shell-api.classes.${className}.help`;
Expand Down Expand Up @@ -145,12 +146,18 @@ export default function constructShellBson(bson: typeof BSON): any {
const buffer = Buffer.from(hexstr, 'hex');
return new bson.Binary(buffer, subtype);
},
UUID: function(hexstr: string): BinaryType {
assertArgsDefined(hexstr);
UUID: function(hexstr?: string): BinaryType {
if (hexstr === undefined) {
// Generate a version 4, variant 1 UUID, like the old shell did.
const uuid = randomBytes(16);
uuid[6] = (uuid[6] & 0x0f) | 0x40;
uuid[8] = (uuid[8] & 0x3f) | 0x80;
hexstr = uuid.toString('hex');
}
assertArgsType([hexstr], ['string']);
// Strip any dashes, as they occur in the standard UUID formatting
// (e.g. 01234567-89ab-cdef-0123-456789abcdef).
const buffer = Buffer.from(hexstr.replace(/-/g, ''), 'hex');
const buffer = Buffer.from((hexstr as string).replace(/-/g, ''), 'hex');
return new bson.Binary(buffer, bson.Binary.SUBTYPE_UUID);
},
MD5: function(hexstr: string): BinaryType {
Expand Down