Uecko_ERP/packages/rdx-ddd/src/value-objects/email-address.ts
2026-04-20 20:56:14 +02:00

58 lines
1.2 KiB
TypeScript

import { Result } from "@repo/rdx-utils";
import { z } from "zod/v4";
import { translateZodValidationError } from "../helpers";
import { ValueObject } from "./value-object";
interface EmailAddressProps {
value: string;
}
export class EmailAddress extends ValueObject<EmailAddressProps> {
static create(value: string): Result<EmailAddress, Error> {
const valueIsValid = EmailAddress.validate(value);
if (!valueIsValid.success) {
return Result.fail(
translateZodValidationError("EmailAddress creation failed", valueIsValid.error)
);
}
return Result.ok(new EmailAddress({ value: valueIsValid.data }));
}
private static validate(value: string) {
const schema = z.email({ message: "Invalid email format" });
return schema.safeParse(value);
}
getLocalPart() {
return this.props.value.split("@")[0] ?? "";
}
getDomain() {
return this.props.value.split("@")[1] ?? "";
}
getDomainExtension() {
return this.getDomain()?.split(".")[1] ?? "";
}
getDomainName() {
return this.getDomain()?.split(".")[0] ?? "";
}
getProps(): string {
return this.props.value;
}
toPrimitive() {
return this.getProps();
}
toString() {
return String(this.props.value);
}
}