Uecko_ERP/apps/server/src/common/domain/value-objects/unique-id.ts

43 lines
1.1 KiB
TypeScript
Raw Normal View History

2025-01-29 19:02:59 +00:00
import { v4 as uuidv4 } from "uuid";
import { z } from "zod";
2025-02-20 18:55:24 +00:00
import { Result } from "../../helpers/result";
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-01-29 19:02:59 +00:00
static create(id?: string, generateOnEmpty: boolean = 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-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));
}
static generate(): UniqueID {
return new UniqueID(uuidv4());
}
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-02-20 18:55:24 +00:00
toString(): string {
return this.props;
2025-02-04 18:25:10 +00:00
}
2025-01-29 19:02:59 +00:00
}