Class EntityBuilder<T, TProps>

Fluent builder for creating Entity instances.

EntityBuilder provides a convenient way to construct entities without repeating boilerplate code for IDs and timestamps. It's especially useful in tests and repositories.

// Create a new entity (generates ID automatically)
const product = EntityBuilder.create<'Product', ProductProps>()
.withProps({ name: 'Laptop', price: 999 })
.build(Product);

// Recreate entity from persistence
const product = EntityBuilder.create<'Product', ProductProps>()
.withId('existing-id')
.withProps({ name: 'Laptop', price: 999 })
.withTimestamps(createdAt, updatedAt)
.build(Product);

Type Parameters

  • T extends string

    Phantom type representing the entity type (e.g., 'User', 'Order')

  • TProps

    Type of the entity's properties

Constructors

Methods

  • Sets the entity's ID. If not called, a new ID will be generated automatically.

    Parameters

    • id: string | EntityId<T>

      EntityId or string ID

    Returns this

    This builder for chaining

  • Sets the entity's properties. This method must be called before build().

    Parameters

    • props: TProps

      Entity properties

    Returns this

    This builder for chaining

  • Sets the entity's timestamps. If not called, current date will be used for both timestamps.

    Parameters

    • OptionalcreatedAt: Date

      Creation timestamp (defaults to now)

    • OptionalupdatedAt: Date

      Last update timestamp (defaults to now)

    Returns this

    This builder for chaining

  • Builds the entity instance.

    Type Parameters

    Parameters

    • EntityClass: new (
          id: EntityId<T>,
          props: TProps,
          createdAt: Date,
          updatedAt: Date,
      ) => TEntity

      Entity constructor that accepts (id, props, createdAt, updatedAt)

    Returns TEntity

    The constructed entity

    Error if props were not set

    const product = builder.build(Product);