diff --git a/src/plugins/database.ts b/src/plugins/database.ts new file mode 100644 index 0000000..2a04f81 --- /dev/null +++ b/src/plugins/database.ts @@ -0,0 +1,32 @@ +import { FastifyInstance, FastifyPluginAsync } from 'fastify'; +import { drizzle } from 'drizzle-orm/node-postgres'; +import pg from 'pg'; +import fp from 'fastify-plugin'; +import { env } from '../config/env.js'; + +const { Pool } = pg; + +declare module 'fastify' { + interface FastifyInstance { + db: ReturnType; + } +} + +const databasePlugin: FastifyPluginAsync = async (app: FastifyInstance) => { + const pool = new Pool({ + connectionString: env.DATABASE_URL, + max: 10, + idleTimeoutMillis: 30000, + connectionTimeoutMillis: 5000, + }); + + const db = drizzle(pool); + + app.decorate('db', db); + + app.addHook('onClose', async () => { + await pool.end(); + }); +}; + +export default fp(databasePlugin, { name: 'database' });