import { Maybe, Result } from "@common/helpers"; import { z } from "zod"; import { ValueObject } from "./value-object"; interface EmailAddressProps { value: string; } export class EmailAddress extends ValueObject { static create(value: string): Result { const valueIsValid = EmailAddress.validate(value); if (!valueIsValid.success) { return Result.fail(new Error(valueIsValid.error.errors[0].message)); } return Result.ok(new EmailAddress({ value: valueIsValid.data! })); } static createNullable(value?: string): Result, Error> { if (!value || value.trim() === "") { return Result.ok(Maybe.none()); } return EmailAddress.create(value!).map((value) => Maybe.some(value)); } private static validate(value: string) { const schema = z.string().email({ message: "Invalid email format" }); return schema.safeParse(value); } getLocalPart(): string { return this.props.value.split("@")[0]; } getDomain(): string { return this.props.value.split("@")[1]; } getDomainExtension(): string { return this.getDomain().split(".")[1]; } getDomainName(): string { return this.getDomain().split(".")[0]; } getValue(): string { return this.props.value; } toString(): string { return this.getValue(); } }