← Builder lesson
Lab

Builder

Sign in to run your code

Read the brief and the starter here. With a free account you can edit it, run the sample, step through it and check your work, and your progress is kept.

// What a search hands to the database: SQL text and its parameters.
type Query = { sql: string; params: string[] };

// Each part of the page (search box, filter chips, sort menu, pager) calls
// the search as the user acts; the list page calls build to load results.
// This one writes its SQL as each call arrives.
class TripSearch {
  private sql = 'SELECT * FROM trips';
  private params: string[] = [];

  filter(field: string, value: string): void {
    this.params.push(value);
    const word = this.params.length === 1 ? 'WHERE' : 'AND';
    this.sql += ` ${word} ${field} = $${this.params.length}`;
  }
  orderBy(field: string): void {
    this.sql += ` ORDER BY ${field}`;
  }
  page(n: number): void {
    this.sql += ` LIMIT 20 OFFSET ${(n - 1) * 20}`;
  }
  build(): Query {
    return { sql: this.sql, params: [...this.params] };
  }
}