@somosphi/uuid
Version:
Utility functions for dealing with UUIDs
44 lines (43 loc) • 1.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const uuid_1 = require("uuid");
/**
* Generates a random v4 UUID.
* @returns the UUID in string format
*/
exports.generate = uuid_1.v4;
/**
* Converts a UUID in string format to binary.
* @param uuidString a valid UUID in string format
* @returns the UUID in binary format
* @throws if the string is not a valid UUID
*/
function stringToBinary(uuidString) {
const hex = uuidString.replace(/-/g, '');
const buffer = Buffer.from(hex, 'hex');
if (buffer.length !== 16) {
throw new Error('Invalid UUID');
}
return buffer;
}
exports.stringToBinary = stringToBinary;
/**
* Converts a UUID in binary format to a string.
* @param uuidBuffer a valid UUID in binary format
* @returns the UUID in string format
* @throws if the buffer is not a valid UUID
*/
function binaryToString(uuidBuffer) {
if (uuidBuffer.length !== 16) {
throw new Error('Invalid UUID');
}
const hex = uuidBuffer.toString('hex');
return [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20, 32),
].join('-');
}
exports.binaryToString = binaryToString;