← Back to scenarios
ScenarioCatalog DB

Configuration assembly

Build a runtime configuration object from many optional settings.

Problem

An application must construct a valid configuration from optional settings without using a large constructor or allowing invalid partial configuration to leak into runtime behavior.

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