Uecko_ERP/packages/rdx-ddd/src/value-objects/unique-id.ts

47 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-07-07 18:25:13 +00:00
import { Result, generateUUIDv4 } from "@repo/rdx-utils";
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-07-07 18:25:13 +00:00
static validate(value: string) {
const schema = z.uuid({ message: "Invalid UUID format" });
return schema.safeParse(value);
}
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))
2025-07-07 18:25:13 +00:00
: Result.fail(new Error(result.error.message));
2025-01-29 19:02:59 +00:00
}
2025-02-25 15:25:30 +00:00
static generate(): Result<UniqueID, never> {
2025-07-07 18:25:13 +00:00
return UniqueID.generateNewID();
2025-01-29 19:02:59 +00:00
}
static generateNewID(): Result<UniqueID, never> {
2025-07-07 18:25:13 +00:00
return Result.ok(new UniqueID(generateUUIDv4()));
2025-01-29 19:02:59 +00:00
}
2025-02-04 18:25:10 +00:00
2025-09-04 10:02:24 +00:00
getProps(): string {
2025-02-20 18:55:24 +00:00
return this.props;
2025-02-04 18:25:10 +00:00
}
2025-04-01 15:32:53 +00:00
toString(): string {
2025-09-05 11:23:45 +00:00
return String(this.getProps());
2025-04-01 15:32:53 +00:00
}
toPrimitive() {
2025-09-05 11:23:45 +00:00
return this.toString();
2025-02-04 18:25:10 +00:00
}
2025-01-29 19:02:59 +00:00
}