Uecko_ERP/packages/rdx-ddd/src/value-objects/name.ts

63 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-05-09 10:45:32 +00:00
import { Maybe, Result } from "@repo/rdx-utils";
2025-06-24 18:38:57 +00:00
import * as z from "zod/v4";
2025-02-21 10:06:27 +00:00
import { ValueObject } from "./value-object";
2025-02-20 18:55:24 +00:00
2025-02-24 19:00:28 +00:00
interface INameProps {
2025-02-20 18:55:24 +00:00
value: string;
}
2025-02-24 19:00:28 +00:00
export class Name extends ValueObject<INameProps> {
2025-02-20 18:55:24 +00:00
private static readonly MAX_LENGTH = 255;
protected static validate(value: string) {
const schema = z
.string()
.trim()
.max(Name.MAX_LENGTH, { message: `Name must be at most ${Name.MAX_LENGTH} characters long` });
return schema.safeParse(value);
}
static create(value: string) {
const valueIsValid = Name.validate(value);
if (!valueIsValid.success) {
2025-08-26 18:55:59 +00:00
return Result.fail(new Error(valueIsValid.error.issues[0].message));
2025-02-20 18:55:24 +00:00
}
2025-02-24 19:00:28 +00:00
return Result.ok(new Name({ value }));
2025-02-20 18:55:24 +00:00
}
static createNullable(value?: string): Result<Maybe<Name>, Error> {
if (!value || value.trim() === "") {
2025-02-25 19:17:30 +00:00
return Result.ok(Maybe.none<Name>());
2025-02-20 18:55:24 +00:00
}
2025-05-09 10:45:32 +00:00
return Name.create(value).map((value) => Maybe.some(value));
2025-02-20 18:55:24 +00:00
}
static generateAcronym(name: string): string {
const words = name.split(" ").map((word) => word[0].toUpperCase());
let acronym = words.join("");
// Asegurarse de que tenga 4 caracteres, recortando o añadiendo letras
if (acronym.length > 4) {
acronym = acronym.slice(0, 4);
} else if (acronym.length < 4) {
acronym = acronym.padEnd(4, "X"); // Se completa con 'X' si es necesario
}
return acronym;
}
getAcronym(): string {
return Name.generateAcronym(this.toString());
}
getValue(): string {
return this.props.value;
}
2025-04-01 14:26:15 +00:00
toPrimitive() {
2025-02-20 18:55:24 +00:00
return this.getValue();
}
}