UNPKG

@synet/patterns

Version:

Robust, battle-tested collection of stable patterns used in Synet packages

69 lines (68 loc) 1.93 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UniqueId = void 0; const result_1 = require("./result"); const uuid_1 = require("uuid"); const value_object_1 = require("./value-object"); /** * Represents a unique identifier. * * UniqueId encapsulates the concept of identity and provides type safety for IDs. * By default, it uses UUID v4, but can accept custom ID values when provided. * * @example * // Generate a new ID * const id = new UniqueId(); * * // Use an existing ID * const existingId = UniqueId.create("550e8400-e29b-41d4-a716-446655440000"); * if (existingId.isSuccess) { * const id = existingId.value; * console.log(id.toString()); // "550e8400-e29b-41d4-a716-446655440000" * } */ class UniqueId extends value_object_1.ValueObject { /** * Creates a new UniqueId. * If no id is provided, generates a new UUID v4. * * @param id Optional existing ID value */ constructor(id) { super({ value: id || (0, uuid_1.v4)() }); } /** * Creates a UniqueId with validation. * * @param id The ID string to validate * @returns A Result containing either the UniqueId or an error */ static create(id) { if (!id) { return result_1.Result.fail("ID cannot be empty"); } if (!(0, uuid_1.validate)(id)) { return result_1.Result.fail("ID must be a valid UUID"); } return result_1.Result.success(new UniqueId(id)); } /** * Returns the string representation of this ID. */ toString() { return this.props.value; } /** * Returns the string representation when converted to JSON. */ toJSON() { return this.toString(); } /** * Creates a deep copy of this UniqueId. */ clone() { return new UniqueId(this.props.value); } } exports.UniqueId = UniqueId;