How fastify/fastify-postgres works
Project type and purpose
• This is an open-source Fastify plugin (@fastify/postgres) that integrates PostgreSQL connection pooling into a Fastify server.
• It wraps the node-postgres (pg) library, exposes methods (connect, query, transact, Client, pool) on the Fastify instance, and manages lifecycle hooks (preHandler, onError, onSend).
File structure
• Top-level:
• index.js / index.d.ts – plugin entry point (register function, option parsing).
• lib/add-handler.js – code that injects connect/query/transact handlers and hooks into Fastify.
• examples/ – sample TypeScript apps demonstrating single-DB, multi-DB, transactions.
• test/ and test-types/ – JavaScript and TypeScript test suites.
• ci_scripts/ – build & install scripts for CI.
• Pattern: a single module exporting a Fastify plugin. It follows Fastify’s plugin architecture, uses hooks to manage transactions.
README for additional insights
• Describes plugin features (connect, query, transact, named connections, native option, custom pg module).
• Explains how the plugin attaches to Fastify, and how it uses Fastify’s lifecycle hooks to manage transactions.
Detail
• Every decoration (fastify.pg, fastify.pg.foo) and lifecycle hook.
• Utility methods (connect, query, transact) and their internal flows (acquire/release, commit/rollback).
• How custom pg module or pg-native option replaces the default pg library.