Uecko_ERP/apps/server/archive/contexts/auth/domain/value-objects/username.ts

42 lines
1.0 KiB
TypeScript
Raw Normal View History

2025-05-02 21:43:51 +00:00
import { ValueObject } from "@/core/common/domain";
2025-05-09 10:45:32 +00:00
import { Result } from "@repo/rdx-utils";
2025-01-29 19:02:59 +00:00
import { z } from "zod";
2025-02-20 18:55:24 +00:00
interface UsernameProps {
value: string;
}
export class Username extends ValueObject<UsernameProps> {
2025-01-29 19:02:59 +00:00
static create(username: string): Result<Username, Error> {
const result = Username.validate(username);
return result.success
2025-02-20 18:55:24 +00:00
? Result.ok(new Username({ value: result.data }))
2025-01-29 19:02:59 +00:00
: Result.fail(new Error(result.error.errors[0].message));
}
private static validate(username: string) {
const schema = z
.string()
.min(3, { message: "Username must be at least 3 characters long" })
.max(30, { message: "Username cannot exceed 30 characters" })
.regex(/^[a-zA-Z0-9_]+$/, {
message: "Username can only contain letters, numbers, and underscores",
});
return schema.safeParse(username);
}
2025-02-20 18:55:24 +00:00
getValue() {
return this.props.value;
}
toString() {
return this.props.value;
}
2025-05-02 21:43:51 +00:00
toPrimitive() {
return this.props.value;
}
2025-01-29 19:02:59 +00:00
}