2025-02-21 10:06:27 +00:00
|
|
|
import { Maybe, Result } from "@common/helpers";
|
2025-02-20 18:55:24 +00:00
|
|
|
import { z } from "zod";
|
2025-02-21 10:06:27 +00:00
|
|
|
import { ValueObject } from "./value-object";
|
2025-02-20 18:55:24 +00:00
|
|
|
|
|
|
|
|
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) {
|
2025-02-24 19:00:28 +00:00
|
|
|
return Result.fail(new Error(valueIsValid.error.errors[0].message));
|
2025-02-20 18:55:24 +00:00
|
|
|
}
|
|
|
|
|
return Result.ok(new EmailAddress({ value: valueIsValid.data! }));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static createNullable(value?: string): Result<Maybe<EmailAddress>, Error> {
|
|
|
|
|
if (!value || value.trim() === "") {
|
|
|
|
|
return Result.ok(Maybe.None<EmailAddress>());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
}
|
2025-02-21 10:06:27 +00:00
|
|
|
|
|
|
|
|
toString(): string {
|
|
|
|
|
return this.getValue();
|
|
|
|
|
}
|
2025-02-20 18:55:24 +00:00
|
|
|
}
|