33 lines
745 B
TypeScript
33 lines
745 B
TypeScript
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<typeof drizzle>;
|
|
}
|
|
}
|
|
|
|
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' });
|