Skip to content

feat(NODE-1046): natively support UUID (de)serialization #465

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
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
8 changes: 6 additions & 2 deletions src/bson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ import { ObjectId } from './objectid';
import { BSONError, BSONTypeError } from './error';
import { calculateObjectSize as internalCalculateObjectSize } from './parser/calculate_size';
// Parts of the parser
import { deserialize as internalDeserialize, DeserializeOptions } from './parser/deserializer';
import {
deserialize as internalDeserialize,
DeserializeOptions,
DefaultDeserializeOptions
} from './parser/deserializer';
import { serializeInto as internalSerialize, SerializeOptions } from './parser/serializer';
import { BSONRegExp } from './regexp';
import { BSONSymbol } from './symbol';
Expand Down Expand Up @@ -77,7 +81,7 @@ export {
TimestampOverrides
} from './timestamp';
export { UUIDExtended } from './uuid';
export { SerializeOptions, DeserializeOptions };
export { SerializeOptions, DeserializeOptions, DefaultDeserializeOptions };
export {
Code,
Map,
Expand Down
21 changes: 16 additions & 5 deletions src/parser/deserializer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Buffer } from 'buffer';
import { Binary } from '../binary';
import type { Document } from '../bson';
import { Document, UUID } from '../bson';
import { Code } from '../code';
import * as constants from '../constants';
import { DBRef, DBRefLike, isDBRefLike } from '../db_ref';
Expand All @@ -17,6 +17,11 @@ import { BSONSymbol } from '../symbol';
import { Timestamp } from '../timestamp';
import { validateUtf8 } from '../validate_utf8';

/** @public */
export const DefaultDeserializeOptions = {
convertUUIDs: false
};

/** @public */
export interface DeserializeOptions {
/** evaluate functions in the BSON document scoped to the object deserialized. */
Expand Down Expand Up @@ -45,6 +50,8 @@ export interface DeserializeOptions {
index?: number;

raw?: boolean;
/** Convert Binary values of subtype 4 to UUID */
convertUUIDs?: boolean;
}

// Internal long versions
Expand Down Expand Up @@ -120,6 +127,8 @@ function deserializeObject(
const promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
const promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];

const convertUUIDs = !!(DefaultDeserializeOptions.convertUUIDs || options.convertUUIDs);

// Set the start index
const startIndex = index;

Expand Down Expand Up @@ -342,10 +351,12 @@ function deserializeObject(
throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
}

if (promoteBuffers && promoteValues) {
value = buffer.slice(index, index + binarySize);
} else {
value = new Binary(buffer.slice(index, index + binarySize), subType);
value = buffer.slice(index, index + binarySize);

if (convertUUIDs && subType === Binary.SUBTYPE_UUID) {
value = new UUID(value);
} else if (!(promoteBuffers && promoteValues)) {
value = new Binary(value, subType);
}
} else {
const _buffer = Buffer.alloc(binarySize);
Expand Down
6 changes: 6 additions & 0 deletions src/parser/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,8 @@ export function serializeInto(
index = serializeInt32(buffer, key, value, index, true);
} else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
index = serializeMinMax(buffer, key, value, index, true);
} else if (value['_bsontype'] === 'UUID') {
index = serializeBinary(buffer, key, value.toBinary(), index);
} else if (typeof value['_bsontype'] !== 'undefined') {
throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
}
Expand Down Expand Up @@ -942,6 +944,8 @@ export function serializeInto(
index = serializeInt32(buffer, key, value, index);
} else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
index = serializeMinMax(buffer, key, value, index);
} else if (value['_bsontype'] === 'UUID') {
index = serializeBinary(buffer, key, value.toBinary(), index);
} else if (typeof value['_bsontype'] !== 'undefined') {
throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
}
Expand Down Expand Up @@ -1048,6 +1052,8 @@ export function serializeInto(
index = serializeInt32(buffer, key, value, index);
} else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
index = serializeMinMax(buffer, key, value, index);
} else if (value['_bsontype'] === 'UUID') {
index = serializeBinary(buffer, key, value.toBinary(), index);
} else if (typeof value['_bsontype'] !== 'undefined') {
throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
}
Expand Down
51 changes: 50 additions & 1 deletion test/node/uuid_tests.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
'use strict';

const { Buffer } = require('buffer');
const { Binary, UUID } = require('../register-bson');
const {
Binary,
UUID,
serialize,
deserialize,
DefaultDeserializeOptions
} = require('../register-bson');
const { inspect } = require('util');
const { validate: uuidStringValidate, version: uuidStringVersion } = require('uuid');
const { afterEach } = require('mocha');

// Test values
const UPPERCASE_DASH_SEPARATED_UUID_STRING = 'AAAAAAAA-AAAA-4AAA-AAAA-AAAAAAAAAAAA';
Expand Down Expand Up @@ -160,4 +167,46 @@ describe('UUID', () => {
const uuid = new UUID(UPPERCASE_DASH_SEPARATED_UUID_STRING);
expect(inspect(uuid)).to.equal(`new UUID("${LOWERCASE_DASH_SEPARATED_UUID_STRING}")`);
});

describe('when (de)serializing', () => {
describe('without specifying any `convertUUIDs` option', () => {
it('should (de)serialize as Binary/4', () => {
const uuidString = 'bd2d74fe-bad8-430c-aeac-b01d073a1eb6';

const { value } = deserialize(serialize({ value: new UUID(uuidString) }));
expect(value).to.be.instanceOf(Binary);
expect(value.toUUID().toHexString()).to.equal(uuidString);
});
});

describe('with DeserializationOptions.convertUUIDs set', () => {
it('should (de)serialize as actual UUID', () => {
const uuidString = 'bd2d74fe-bad8-430c-aeac-b01d073a1eb6';

const { value } = deserialize(serialize({ value: new UUID(uuidString) }), {
convertUUIDs: true
});
expect(value).to.be.instanceOf(UUID);
expect(value.toHexString()).to.equal(uuidString);
});
});

describe('with `DefaultDeserializationOption.convertUUIDs` set', () => {
beforeEach(() => {
DefaultDeserializeOptions.convertUUIDs = true;
});

afterEach(() => {
DefaultDeserializeOptions.convertUUIDs = false;
});

it('should (de)serialize as actual UUID', () => {
const uuidString = 'bd2d74fe-bad8-430c-aeac-b01d073a1eb6';

const { value } = deserialize(serialize({ value: new UUID(uuidString) }));
expect(value).to.be.instanceOf(UUID);
expect(value.toHexString()).to.equal(uuidString);
});
});
});
});