harden business rules
This commit is contained in:
42
core/racing/domain/value-objects/DriverName.ts
Normal file
42
core/racing/domain/value-objects/DriverName.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { IValueObject } from "../../../shared/domain/ValueObject";
|
||||
|
||||
export interface DriverNameProps {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export class DriverName implements IValueObject<DriverNameProps> {
|
||||
private static readonly MIN_LENGTH = 1;
|
||||
private static readonly MAX_LENGTH = 50;
|
||||
private static readonly VALID_CHARACTERS = /^[a-zA-Z0-9\s\-_]+$/;
|
||||
|
||||
private constructor(public readonly props: DriverNameProps) {}
|
||||
|
||||
static create(name: string): DriverName {
|
||||
const trimmed = name.trim();
|
||||
|
||||
if (trimmed.length < this.MIN_LENGTH) {
|
||||
throw new Error(`Driver name must be at least ${this.MIN_LENGTH} character long`);
|
||||
}
|
||||
|
||||
if (trimmed.length > this.MAX_LENGTH) {
|
||||
throw new Error(`Driver name must not exceed ${this.MAX_LENGTH} characters`);
|
||||
}
|
||||
|
||||
if (!this.VALID_CHARACTERS.test(trimmed)) {
|
||||
throw new Error("Driver name can only contain letters, numbers, spaces, hyphens, and underscores");
|
||||
}
|
||||
|
||||
return new DriverName({ value: trimmed });
|
||||
}
|
||||
|
||||
equals(other: IValueObject<DriverNameProps>): boolean {
|
||||
if (!(other instanceof DriverName)) {
|
||||
return false;
|
||||
}
|
||||
return this.props.value === other.props.value;
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return this.props.value;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user