2025-05-09 10:45:32 +00:00
|
|
|
import { Result } from "@repo/rdx-utils";
|
2025-01-29 19:02:59 +00:00
|
|
|
import { v4 as uuidv4 } from "uuid";
|
2025-06-24 18:38:57 +00:00
|
|
|
import * as z from "zod/v4";
|
2025-01-29 19:02:59 +00:00
|
|
|
import { ValueObject } from "./value-object";
|
|
|
|
|
|
2025-02-20 18:55:24 +00:00
|
|
|
export class UniqueID extends ValueObject<string> {
|
2025-05-04 20:06:57 +00:00
|
|
|
static create(id?: string, generateOnEmpty = false): Result<UniqueID, Error> {
|
2025-02-20 18:55:24 +00:00
|
|
|
if (!id || id?.trim() === "") {
|
|
|
|
|
if (!generateOnEmpty) {
|
|
|
|
|
return Result.fail(new Error("ID cannot be undefined or null"));
|
|
|
|
|
}
|
2025-02-24 19:00:28 +00:00
|
|
|
return UniqueID.generateNewID();
|
2025-01-29 19:02:59 +00:00
|
|
|
}
|
|
|
|
|
|
2025-05-09 10:45:32 +00:00
|
|
|
// biome-ignore lint/style/noNonNullAssertion: <explanation>
|
2025-02-20 18:55:24 +00:00
|
|
|
const result = UniqueID.validate(id!);
|
2025-01-29 19:02:59 +00:00
|
|
|
|
|
|
|
|
return result.success
|
|
|
|
|
? Result.ok(new UniqueID(result.data))
|
|
|
|
|
: Result.fail(new Error(result.error.errors[0].message));
|
|
|
|
|
}
|
|
|
|
|
|
2025-02-25 15:25:30 +00:00
|
|
|
static generate(): Result<UniqueID, never> {
|
|
|
|
|
return Result.ok(new UniqueID(uuidv4()));
|
2025-01-29 19:02:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static validate(id: string) {
|
2025-02-20 18:55:24 +00:00
|
|
|
const schema = z.string().trim().uuid({ message: "Invalid UUID format" });
|
|
|
|
|
return schema.safeParse(id);
|
2025-01-29 19:02:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static generateNewID(): Result<UniqueID, never> {
|
|
|
|
|
return Result.ok(new UniqueID(uuidv4()));
|
|
|
|
|
}
|
2025-02-04 18:25:10 +00:00
|
|
|
|
2025-02-20 18:55:24 +00:00
|
|
|
getValue(): string {
|
|
|
|
|
return this.props;
|
2025-02-04 18:25:10 +00:00
|
|
|
}
|
|
|
|
|
|
2025-04-01 15:32:53 +00:00
|
|
|
toString(): string {
|
|
|
|
|
return this.getValue();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
toPrimitive() {
|
|
|
|
|
return this.getValue();
|
2025-02-04 18:25:10 +00:00
|
|
|
}
|
2025-01-29 19:02:59 +00:00
|
|
|
}
|