Do not multiply the builder

Typescript builder tutorial [3/6]

Introduction

As a lazy developer, we do not want to have to create one builder for each business entity present in our application. Here again Typescript generic will come for help, in order to maximize the reuse of our code. Let see how it can be done.

Reuse !

Our first step will be to move in the EntityBuilder class all the static methods from the Ingreditent & Recipe builder and getting ride off the IngredientBuilder & RecipeBuilder classes.


export default class EntityBuilder<BuiltEntityType> {

  public static getA<StaticBuiltEntityType>(TCreator: new () => StaticBuiltEntityType) {
    return new EntityBuilder(TCreator)
  }

  public static getAn<StaticBuiltEntityType>(TCreator: new () => StaticBuiltEntityType) {
    return EntityBuilder.getA(TCreator)
  }

  protected builtEntity: Partial<BuiltEntityType>
  private creator: new () => BuiltEntityType

  constructor(TCreator: new () => BuiltEntityType) {
    this.creator = TCreator
    this.builtEntity = new this.creator()
  }

  public build() {
    const returnedObj = this.builtEntity
    this.builtEntity = new this.creator()
    return returnedObj
  }
}

Conclusion

By doing so we can create an entity that is using directly the EntityBuilder class, be we cannot do much more and the following sample demonstrates this :

Step 2 - No way to valuate properties.png

If you are already familiar with advanced typescript features and just want to see what could be a convenient-to-use builder infrastructure that makes good use of those features, please have a look at this repo : berlingo-ts