Uecko_ERP/packages/rdx-ddd/src/value-objects/email-address.ts

57 lines
1.3 KiB
TypeScript
Raw Normal View History

2025-05-09 10:45:32 +00:00
import { Maybe, Result } from "@repo/rdx-utils";
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
}
2025-05-09 10:45:32 +00:00
return Result.ok(new EmailAddress({ value: valueIsValid.data }));
2025-02-20 18:55:24 +00:00
}
static createNullable(value?: string): Result<Maybe<EmailAddress>, Error> {
if (!value || value.trim() === "") {
2025-02-25 19:17:30 +00:00
return Result.ok(Maybe.none<EmailAddress>());
2025-02-20 18:55:24 +00:00
}
2025-05-09 10:45:32 +00:00
return EmailAddress.create(value).map((value) => Maybe.some(value));
2025-02-20 18:55:24 +00:00
}
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
2025-04-01 14:26:15 +00:00
toPrimitive() {
2025-02-21 10:06:27 +00:00
return this.getValue();
}
2025-02-20 18:55:24 +00:00
}