import fp from 'fastify-plugin'; import pg from 'pg'; import { Kysely, PostgresDialect } from 'kysely'; import type { Database } from '../db/schema'; // Parse int8 (OID 20) as a JS number. Safe well past any realistic message // count (Number.MAX_SAFE_INTEGER ≈ 9e15); revisit if a counter could exceed it. pg.types.setTypeParser(20, (value) => Number(value)); declare module 'fastify' { interface FastifyInstance { db: Kysely; } } // Postgres connection pool wrapped in a typed Kysely instance. Registered via // fastify-plugin so the `db` decoration is visible app-wide, not just in scope. export const dbPlugin = fp( (app) => { const pool = new pg.Pool({ connectionString: app.config.databaseUrl }); const db = new Kysely({ dialect: new PostgresDialect({ pool }) }); app.decorate('db', db); app.addHook('onClose', async () => { await db.destroy(); }); return Promise.resolve(); }, { name: 'db' }, );