✔️
types-ddd
  • Introduction
  • Result
    • ok
    • success
    • fail
    • combine
  • UniqueEntityID
  • BaseDomainEntity
  • ValueObject
  • Entity
  • AggregateRoot
    • IHandle
    • IDomainEvent
    • DomainEvents
  • WriteList
    • ReadList
  • IUseCase
  • IBaseConnection
  • BaseRepository
  • IRepository
  • Filter
  • IMapper
  • Utils
    • SpecificationComposite
    • ChangesObserver
Powered by GitBook
On this page

Was this helpful?

Entity

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();
Accessible attributes for car
> car.color
> car.createdAt
> car.deletedAt
> car.equals
> car.id
> car.isDeleted
> car.isValidYear
> car.updatedAt
> car.year
> car.getHashCode
> car.toObject
PreviousValueObjectNextAggregateRoot

Last updated 3 years ago

Was this helpful?