Messenger/packages/backend/src/plugins/db.ts
Заид Омар Медхат | Zaid Omar Medhat e7f37be62c simple chat init
2026-07-10 15:32:34 +05:00

31 lines
974 B
TypeScript

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<Database>;
}
}
// 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<Database>({ dialect: new PostgresDialect({ pool }) });
app.decorate('db', db);
app.addHook('onClose', async () => {
await db.destroy();
});
return Promise.resolve();
},
{ name: 'db' },
);