← Back to scenarios
ScenarioCatalog DB

Document composition

Assemble invoices, contracts, or letters from reusable document sections.

Problem

A document pipeline must compose documents from optional reusable sections while keeping document construction independent of a specific final document type.

Related patterns

Implementations

Builder

TypeScriptApplication

Builder in TypeScript

Builds an immutable deployment configuration step by step while keeping construction details separate from the final configuration object.

TypeScript
type DeploymentConfig = {
  serviceName: string;
  replicas: number;
  environment: "development" | "staging" | "production";
  healthCheckPath?: string;
};

class DeploymentConfigBuilder {
  private serviceName?: string;
  private replicas = 1;
  private environment: DeploymentConfig["environment"] = "development";
  private healthCheckPath?: string;

  withServiceName(serviceName: string) {
    this.serviceName = serviceName;
    return this;
  }

  withReplicas(replicas: number) {
    this.replicas = replicas;
    return this;
  }

  forEnvironment(environment: DeploymentConfig["environment"]) {
    this.environment = environment;
    return this;
  }

  withHealthCheck(path: string) {
    this.healthCheckPath = path;
    return this;
  }

  build(): DeploymentConfig {
    if (!this.serviceName) {
      throw new Error("A service name is required.");
    }

    return {
      serviceName: this.serviceName,
      replicas: this.replicas,
      environment: this.environment,
      healthCheckPath: this.healthCheckPath,
    };
  }
}

const productionConfig = new DeploymentConfigBuilder()
  .withServiceName("billing-api")
  .withReplicas(3)
  .forEnvironment("production")
  .withHealthCheck("/health")
  .build();

Associated technologies