Live longer than the application, should endure restarts, and are persisted and read from data sources (DB, file system, network, etc.)
Have an id (preferably a GUID rather than a DB generated int because business transactions do not rely on persistence, can be persisted after other operations carried out in model's behavior)
import {
BaseDomainEntity,
Entity,
UniqueEntityID,
Result
} from 'types-ddd';
interface CarProps extends BaseDomainEntity {
year: CarYearValueObject;
color: CarColorValueObject;
}
class Car extends Entity<CarProps> {
private constructor(props: CarProps) {
super (props, Car.name)
}
get year (): CarYearValueObject {
return this.props.year;
}
setYear (year: number): void {
this.props.year = year;
}
get color (): CarColorValueObject {
return this.props.color;
}
setColor (color: CarColorValueObject): void {
this.props.color = color;
}
public static isValidYear (year: number): boolean {
return year > 1920;
}
public static create (props: CarProps): Result<Car> {
// Business logic validation. Just for example!
// Some rules should be validated on the value object
if (!Car.isValidYear(props.year.value)) {
return Result.fail<Car>('Invalid year for a car');
}
return Result.ok<Car>(new Car(props));
}
}
const car = Car.create({ ... }).getResult();