This page provides a step-by-step guide for integrating @primebrick/dal-pg into a TypeScript project. It covers installation, environment configuration, entity definition, and basic database operations using the Dal gateway.
Installation
The package is managed via pnpm and requires reflect-metadata to support decorator-based entity definitions.
Code
pnpm install @primebrick/dal-pg reflect-metadata
TypeScript Configuration
Ensure your tsconfig.json includes the following settings to support the metadata system used by the DAL:
The DAL requires a valid PostgreSQL connection string. By convention, this is stored in a .env file or provided via the DATABASE_URL environment variable.
The Dal class serves as the process-wide entry point. It manages the connection pool, registers type parsers (such as INT8 to bigint conversion), and enforces best-practice defaults like statement_timeout to prevent pool starvation src/dal/dal.ts:4-22.
Setup Example
Code
import "reflect-metadata"; // Must be imported at the entry pointimport { getDal } from "@primebrick/dal-pg";const dal = getDal({ connectionString: process.env.DATABASE_URL!, schema: "public", max: 10, // Max pool size statementTimeoutMs: 30000, // 30s timeout per query applicationName: "my-service"});// Graceful shutdownprocess.on("SIGTERM", async () => { await dal.close(); process.exit(0);});
Gateway Lifecycle and Data Flow
The following diagram illustrates how the Dal gateway initializes the system and bridges the application to the PostgreSQL database.
Entities are plain TypeScript classes decorated with metadata. The DAL uses these decorators to map class properties to database columns and handle specialized logic like auditing and soft-deletion.
The Dal instance provides high-level methods for CRUD operations. All write operations utilize RETURNING * to ensure the returned object reflects the database state README.md:43-43.
The DAL throws specific error classes defined in @primebrick/dal-pg/errors. By default, finder methods like findById or findByUUID throw a NotFoundError if the record does not exist README.md:44-44.
Code
import { NotFoundError } from "@primebrick/dal-pg";try { await dal.findByUUID(UserAccount, "some-uuid");} catch (err) { if (err instanceof NotFoundError) { console.error("User not found in database."); }}