✔️
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?

ValueObject

Can be used to measure or describe things (name, description, amount, height, date, time, range, address, etc.)

ValueObjects are only identified by their values, (for example money is a value object as long as we are not tracking individual banknotes, if we need to track individual banknotes then it should be a banknote entity)

Basically, they are all the attributes you need to validate the status and they don't have a unique ID

import { Result, ValueObject } from 'types-ddd';

interface Prop {
  value: string;
}

class EmailValueObject extends ValueObject<Prop> {
  private constructor(prop: Prop) {
    super(prop);
  }

  get value(): string {
    return this.props.value;
  }

  public static isValidEmail (email: string): boolean {
    const regex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g;
    return regex.test(email);
  }
  
  public static create(value: string): Result<EmailValueObject> {
    
    const isValid = EmailValueObject.isValidEmail(value);
    
    if (!isValid) {
      return Result.fail<EmailValueObject>('Invalid email');
    }
    
    return Result.ok<EmailValueObject>(
      new EmailValueObject({ value: value.toLowerCase() }),
    );
    
  }
}

Lets test our ValueObject

const emailOrError = EmailValueObject.create("valid_email@domain.com");

console.log(emailOrError);
> Result: {
  "isSuccess": true,
  "isFailure": false,
  "error": null,
  "statusCode": "OK",
  "statusCodeNumber": 200,
  "_value": {
    "props": {
      "value": "valid_email@domain.com"
    }
  }
} 

Now lets see a fail example

const emailOrError = EmailValueObject.create("invalid_email");

console.log(emailOrError);
> Result: {
  "isSuccess": false,
  "isFailure": true,
  "error": "Invalid email",
  "_value": null,
  "statusCodeNumber": 422,
  "statusCode": "UNPROCESSABLE_ENTITY"
} 

How to get the ValueObject value

You always have to validate if the result is a failure before getting the result

emailOrError.isFailure;

> false
const emailOrError = EmailValueObject.create("valid_email@domain.com");

const emailValueObject = emailOrError.getResult();

console.log(emailValueObject.value);

> "valid_email@domain.com"

PreviousBaseDomainEntityNextEntity

Last updated 3 years ago

Was this helpful?