uuid_utils.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. import { Buffer } from 'buffer';
  2. import { BSONTypeError } from './error';
  3. // Validation regex for v4 uuid (validates with or without dashes)
  4. const VALIDATION_REGEX =
  5. /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i;
  6. export const uuidValidateString = (str: string): boolean =>
  7. typeof str === 'string' && VALIDATION_REGEX.test(str);
  8. export const uuidHexStringToBuffer = (hexString: string): Buffer => {
  9. if (!uuidValidateString(hexString)) {
  10. throw new BSONTypeError(
  11. 'UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'
  12. );
  13. }
  14. const sanitizedHexString = hexString.replace(/-/g, '');
  15. return Buffer.from(sanitizedHexString, 'hex');
  16. };
  17. export const bufferToUuidHexString = (buffer: Buffer, includeDashes = true): string =>
  18. includeDashes
  19. ? buffer.toString('hex', 0, 4) +
  20. '-' +
  21. buffer.toString('hex', 4, 6) +
  22. '-' +
  23. buffer.toString('hex', 6, 8) +
  24. '-' +
  25. buffer.toString('hex', 8, 10) +
  26. '-' +
  27. buffer.toString('hex', 10, 16)
  28. : buffer.toString('hex');