Search⌘ K
AI Features

Solution: Design a URL Builder with Conditional Parameters

Explore how to use the Builder pattern to create a URL builder class in Node.js. Understand how to fluently add conditional query parameters like pagination, sorting, and filters while ensuring valid URLs. Learn to manage required fields, chain method calls, and generate properly encoded URLs.

Solution explanation

  • Lines 2–6: We initialize an internal state with baseparams, and filters, keeping URL segments separate. The base must be explicitly provided before building.

  • Lines 8–31: We define fluent setter methods for different URL components.

    • withPagewithLimit, and sortBy add pagination and sorting options to params.

    • filterBy stores filter key-value pairs, supporting multiple dynamic filters.

    • Each method returns this, enabling flexible chaining. ...