Wiring PostgreSQL Products

Lesson: Wiring PostgreSQL Products

Welcome back 👋 Up to now, your /api/products endpoint has been about reliable API behavior: validating query parameters and returning consistent success(...) / error(...) envelopes. In Unit 2, you also introduced domain models and DTOs, so your backend has a clear “source of truth” for product data and a clear boundary around what clients are allowed to send.

In this lesson, we finally connect products to PostgreSQL. You’ll walk through the entire pipeline—route → service → repository → database—and, just as importantly, you’ll learn the core database concepts behind the code: what a pool is, why we use a lazy singleton, how queries run without leaking connections, and how raw Postgres errors become stable API failures.

The Big Picture: One Request, Four Layers

When the browser calls GET /api/products, your backend doesn’t jump straight into SQL. It moves through layers that keep responsibilities clear:

  • Route (HTTP layer): validates query params and turns results into success(...) or error(...).
  • Service (workflow layer): applies defaults and converts exceptions into structured results (ok(...) / fail(...)).
  • Repository (data access layer): runs SQL and maps database rows into domain Product objects.
  • DB client (infrastructure layer): manages connection pooling and provides query/transaction helpers.

This structure pays off immediately: your route stays readable, and the database code stays centralized and reusable.

Database Connection Configuration: Environment Variables and Defaults

Before you can query Postgres, your app needs to know where the database is and how to authenticate.

That information comes from environment variables (values provided to the running process, not hardcoded in your code). They’re accessed in Node.js through process.env.

The logic for building the connection string is in src/lib/db/client.ts.

Building a database URL from environment variables

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal