szdytom a03cf1b2a1
[js] add UUID and type-handlers
Signed-off-by: szdytom <szdytom@qq.com>
2024-02-10 14:16:27 +08:00

50 lines
1.6 KiB
JavaScript

import { v4 as uuidv4, v5 as uuidv5, stringify, parse } from 'uuid';
import { Buffer } from 'buffer';
/**
* Represents a UUID (Universally Unique Identifier) object.
*/
export class UUID {
/**
* Constructs a UUID object.
* @param {string|ArrayBuffer} input - The input to construct the UUID from. It can be either a hexadecimal string or an ArrayBuffer.
* @throws {Error} Will throw an error if the input type is invalid. Input must be either a string or an ArrayBuffer.
*/
constructor(input) {
if (typeof input === 'string') {
this.buffer = parse(input);
} else if (input instanceof ArrayBuffer) {
this.buffer = Buffer.from(input);
} else if (input instanceof UUID) {
this.buffer = Buffer.from(input.buffer);
} else {
throw new Error('Invalid input type. Input must be either a string or an ArrayBuffer.');
}
}
/**
* Generates a random UUID using version 4 (random).
* @returns {UUID} A UUID object representing a randomly generated UUID.
*/
static v4() {
return new UUID(uuidv4());
}
/**
* Generates a UUID using version 5 (namespace-based) with the specified namespace and name.
* @param {string} name - The name to be used for generating the UUID.
* @param {string|Buffer|UUID} namespace - The namespace UUID in string or Buffer format.
* @returns {UUID} A UUID object representing a version 5 UUID.
*/
static v5(name, namespace) {
return new UUID(uuidv5(name, new UUID(namespace).toString()));
}
/**
* Converts the UUID object to a string representation.
* @returns {string} A hexadecimal string representation of the UUID.
*/
toString() {
return stringify(this.buffer);
}
};