Skip to content
BBaskaran

Builder

Construct complex objects step by step, separating construction from representation.

Use it when

An object has many optional parts or needs different representations.

/**
 * Builder: assemble an HTTP request step by step, then build it in one go.
 *
 * Real-world scenario: an API client. A request needs a URL, and may have a
 * method, headers, query parameters, a JSON body and a timeout. Instead of a
 * constructor with many optional arguments, the builder sets only the parts you
 * need, checks they make sense in build(), and returns a finished request.
 */

type JsonBody = Record<string, unknown>;

// Product: the finished request. readonly, so its fields can't be reassigned.
class HttpRequest {
  readonly method: string;
  readonly url: string;
  readonly headers: Readonly<Record<string, string>>;
  readonly body: JsonBody | undefined;
  readonly timeout: number;

  constructor(
    method: string,
    url: string,
    headers: Record<string, string>,
    body: JsonBody | undefined,
    timeout: number,
  ) {
    this.method = method;
    this.url = url;
    this.headers = headers;
    this.body = body;
    this.timeout = timeout;
  }

  describe(): string {
    const lines = [`${this.method} ${this.url} (timeout ${this.timeout.toFixed(1)}s)`];
    for (const [name, value] of Object.entries(this.headers)) {
      lines.push(`  ${name}: ${value}`);
    }
    if (this.body !== undefined) {
      lines.push(`  body: ${JSON.stringify(this.body)}`);
    }
    return lines.join("\n");
  }
}

// Builder: each step sets one part and returns `this`, so calls can be chained.
class HttpRequestBuilder {
  private readonly url: string;
  private httpMethod = "GET";
  private readonly headers: Record<string, string> = {};
  private readonly params = new URLSearchParams();
  private body: JsonBody | undefined;
  private timeoutSeconds = 10;

  constructor(url: string) {
    this.url = url;
  }

  method(method: string): this {
    this.httpMethod = method.toUpperCase();
    return this;
  }

  header(name: string, value: string): this {
    this.headers[name] = value;
    return this;
  }

  bearerToken(token: string): this {
    return this.header("Authorization", `Bearer ${token}`);
  }

  param(name: string, value: string): this {
    this.params.append(name, value);
    return this;
  }

  jsonBody(body: JsonBody): this {
    this.body = body;
    return this.header("Content-Type", "application/json");
  }

  timeout(seconds: number): this {
    this.timeoutSeconds = seconds;
    return this;
  }

  build(): HttpRequest {
    // Validate the whole request once, before anyone can use it.
    if (this.body !== undefined && this.httpMethod === "GET") {
      throw new Error("A GET request can't have a body");
    }
    // URLSearchParams joins pairs with "&" and escapes special characters.
    const query = this.params.toString();
    const url = query ? `${this.url}?${query}` : this.url;
    const headers = { ...this.headers }; // a copy, so later builder calls can't change it
    return new HttpRequest(this.httpMethod, url, headers, this.body, this.timeoutSeconds);
  }
}

function clientCode(): void {
  // Simple request: only the parts that differ from the defaults.
  const search = new HttpRequestBuilder("https://api.bjbaskar.com/products")
    .param("category", "books")
    .param("page", "2")
    .build();
  console.log(search.describe());

  // Detailed request: same builder, more steps.
  const order = new HttpRequestBuilder("https://api.bjbaskar.com/orders")
    .method("post")
    .bearerToken("abc123")
    .jsonBody({ product_id: 42, quantity: 1 })
    .timeout(5)
    .build();
  console.log(order.describe());

  // Invalid combinations are caught at build(), not later at send time.
  try {
    new HttpRequestBuilder("https://api.bjbaskar.com/products").jsonBody({}).build();
  } catch (error) {
    console.log(`Rejected: ${(error as Error).message}`);
  }
}

clientCode();

// Output:
// GET https://api.bjbaskar.com/products?category=books&page=2 (timeout 10.0s)
// POST https://api.bjbaskar.com/orders (timeout 5.0s)
//   Authorization: Bearer abc123
//   Content-Type: application/json
//   body: {"product_id":42,"quantity":1}
// Rejected: A GET request can't have a body

How it works

RoleClassesWhat it does
ProductHttpRequestThe finished request; readonly, so its fields can't be reassigned
BuilderHttpRequestBuilderChainable steps that return this, and a build() that validates
ClientclientCode()Sets only the parts it needs, then calls build()