typescript

Builder Pattern

Type-safe builder pattern with method chaining

Tarun Sharma
Tarun SharmaJanuary 15, 2024 · 1 min read · Last Updated:
interface QueryConfig {
  table: string;
  select: string[];
  where?: Record<string, unknown>;
  orderBy?: string;
  limit?: number;
}

class QueryBuilder {
  private config: Partial<QueryConfig> = {};

  from(table: string): this {
    this.config.table = table;
    return this;
  }

  select(...fields: string[]): this {
    this.config.select = fields;
    return this;
  }

  where(conditions: Record<string, unknown>): this {
    this.config.where = conditions;
    return this;
  }

  orderBy(field: string): this {
    this.config.orderBy = field;
    return this;
  }

  limit(count: number): this {
    this.config.limit = count;
    return this;
  }

  build(): QueryConfig {
    if (!this.config.table || !this.config.select) {
      throw new Error('table and select are required');
    }
    return this.config as QueryConfig;
  }
}

Usage

const query = new QueryBuilder()
  .from('users')
  .select('id', 'name', 'email')
  .where({ active: true })
  .orderBy('createdAt')
  .limit(10)
  .build();

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Tarun Sharma

Written byTarun Sharma
Full-stack developer and tech educator with 10+ years of experience building scalable applications. Passionate about Node.js, NestJS, React, and cloud technologies. Creator of 50+ courses on Udemy and active YouTube educator helping developers level up their skills.
Connect

Is this page helpful?

Related VideosView All

Stack Overflow Clone - APIs Integration Redux Toolkit [Closure] - App Demo #05

Become Ninja Developer - API security Best Practices with Node JS Packages #15

Nest JS Microservices using HTTP Gateway and Redis Services (DEMO) #nestjs #microservices #16