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

62 lines
1.4 KiB
TypeScript
Raw Normal View History

2026-02-12 14:46:47 +00:00
import {
Result,
generateUUIDv7,
isUuidBinary,
uuidBinaryToString,
uuidStringToBinary,
} from "@repo/rdx-utils";
2025-09-24 17:30:35 +00:00
import { z } from "zod/v4";
2026-02-12 14:46:47 +00:00
2025-09-22 16:35:42 +00:00
import { translateZodValidationError } from "../helpers";
2026-02-12 14:46:47 +00:00
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);
}
2026-02-12 14:46:47 +00:00
static create(id?: string | Buffer, generateOnEmpty = false): Result<UniqueID, Error> {
const _id = isUuidBinary(id) ? uuidBinaryToString(id) : id;
if (!_id || _id?.trim() === "") {
2025-02-20 18:55:24 +00:00
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>
2026-02-12 14:46:47 +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(generateUUIDv7());
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
}
2026-02-12 14:46:47 +00:00
toBuffer(): Buffer {
return uuidStringToBinary(this.toString());
}
2025-01-29 19:02:59 +00:00
}