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

48 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-09-24 17:30:35 +00:00
import { z } from "zod/v4";
2025-09-22 16:35:42 +00:00
import { translateZodValidationError } from "../helpers";
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-09-22 16:35:42 +00:00
return Result.ok(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-09-22 16:35:42 +00:00
const valueIsValid = UniqueID.validate(id!);
2025-01-29 19:02:59 +00:00
2025-09-22 16:35:42 +00:00
if (!valueIsValid.success) {
return Result.fail(
translateZodValidationError("UniqueID creation failed", valueIsValid.error)
);
}
2025-01-29 19:02:59 +00:00
2025-09-22 16:35:42 +00:00
return Result.ok(new UniqueID(valueIsValid.data));
2025-01-29 19:02:59 +00:00
}
2025-09-22 16:35:42 +00:00
static generateNewID(): UniqueID {
return 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
}