Uecko_ERP/packages/rdx-ddd/src/value-objects/currency-code.ts
2025-09-16 13:29:45 +02:00

60 lines
1.4 KiB
TypeScript

import { Result } from "@repo/rdx-utils";
import * as z from "zod/v4";
import { translateZodValidationError } from "../helpers";
import { ValueObject } from "./value-object";
interface CurrencyCodeProps {
value: string;
}
/**
* ISO 4217 Currency Codes
*/
export class CurrencyCode extends ValueObject<CurrencyCodeProps> {
private static readonly MIN_LENGTH = 3;
private static readonly MAX_LENGTH = 3;
protected static validate(value: string) {
const schema = z
.string()
.trim()
.uppercase()
.min(CurrencyCode.MIN_LENGTH, {
message: `CurrencyCode must be at least ${CurrencyCode.MIN_LENGTH} characters long`,
})
.max(CurrencyCode.MAX_LENGTH, {
message: `CurrencyCode must be at most ${CurrencyCode.MAX_LENGTH} characters long`,
});
return schema.safeParse(value);
}
static create(value: string): Result<CurrencyCode, Error> {
const valueIsValid = CurrencyCode.validate(value);
if (!valueIsValid.success) {
return Result.fail(
translateZodValidationError("CurrencyCode creation failed", valueIsValid.error)
);
}
return Result.ok(new CurrencyCode({ value: valueIsValid.data }));
}
get code(): string {
return this.props.value;
}
getProps(): string {
return this.props.value;
}
toPrimitive(): string {
return this.props.value;
}
toString(): string {
return String(this.props.value);
}
}