49 lines
1.2 KiB
TypeScript
49 lines
1.2 KiB
TypeScript
import { Result } from "@repo/rdx-utils";
|
|
import * as z from "zod/v4";
|
|
import { ValueObject } from "./value-object";
|
|
|
|
interface LanguageCodeProps {
|
|
value: string;
|
|
}
|
|
|
|
/**
|
|
* ISO 639-1 (2 letras)
|
|
*/
|
|
|
|
export class LanguageCode extends ValueObject<LanguageCodeProps> {
|
|
private static readonly MIN_LENGTH = 2;
|
|
private static readonly MAX_LENGTH = 2;
|
|
|
|
protected static validate(value: string) {
|
|
const schema = z
|
|
.string()
|
|
.trim()
|
|
.lowercase()
|
|
.min(LanguageCode.MIN_LENGTH, {
|
|
message: `LanguageCode must be at least ${LanguageCode.MIN_LENGTH} characters long`,
|
|
})
|
|
.max(LanguageCode.MAX_LENGTH, {
|
|
message: `LanguageCode must be at most ${LanguageCode.MAX_LENGTH} characters long`,
|
|
});
|
|
|
|
return schema.safeParse(value);
|
|
}
|
|
|
|
static create(value: string): Result<LanguageCode, Error> {
|
|
const valueIsValid = LanguageCode.validate(value);
|
|
|
|
if (!valueIsValid.success) {
|
|
return Result.fail(new Error(valueIsValid.error.issues[0].message));
|
|
}
|
|
return Result.ok(new LanguageCode({ value: valueIsValid.data }));
|
|
}
|
|
|
|
getProps(): string {
|
|
return this.props.value;
|
|
}
|
|
|
|
toPrimitive(): string {
|
|
return this.props.value;
|
|
}
|
|
}
|