Uecko_ERP/apps/server/src/common/domain/value-objects/postal-address.ts

96 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-02-20 18:55:24 +00:00
import { z } from "zod";
import { Maybe, Result } from "../../helpers";
import { ValueObject } from "./value-object";
// 📌 Validaciones usando `zod`
const postalCodeSchema = z
.string()
2025-02-25 10:16:34 +00:00
.min(4, "Invalid postal code format")
.max(10, "Invalid postal code format")
2025-02-20 18:55:24 +00:00
.regex(/^\d{4,10}$/, {
message: "Invalid postal code format",
});
const countrySchema = z.string().min(2).max(56);
const provinceSchema = z.string().min(2).max(50);
const citySchema = z.string().min(2).max(50);
const streetSchema = z.string().min(2).max(255);
interface IPostalAddressProps {
street: string;
city: string;
postalCode: string;
state: string;
country: string;
}
export interface IPostalAddressPrimitives extends IPostalAddressProps {
street: string;
city: string;
postal_code: string;
state: string;
country: string;
}
export class PostalAddress extends ValueObject<IPostalAddressProps> {
protected static validate(values: IPostalAddressProps) {
return z
.object({
street: streetSchema,
city: citySchema,
postalCode: postalCodeSchema,
state: provinceSchema,
country: countrySchema,
})
.safeParse(values);
}
static create(values: IPostalAddressProps): Result<PostalAddress, Error> {
const valueIsValid = PostalAddress.validate(values);
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 PostalAddress(valueIsValid.data!));
}
static createNullable(values?: IPostalAddressProps): Result<Maybe<PostalAddress>, Error> {
if (!values || Object.values(values).every((value) => value.trim() === "")) {
return Result.ok(Maybe.None<PostalAddress>());
}
return PostalAddress.create(values!).map((value) => Maybe.Some(value));
}
get street(): string {
return this.props.street;
}
get city(): string {
return this.props.city;
}
get postalCode(): string {
return this.props.postalCode;
}
get state(): string {
return this.props.state;
}
get country(): string {
return this.props.country;
}
getValue(): IPostalAddressProps {
return this.props;
}
toString(): string {
return `${this.props.street}, ${this.props.city}, ${this.props.postalCode}, ${this.props.state}, ${this.props.country}`;
}
}