feat: add database plugin with Drizzle
Made-with: Cursor
This commit is contained in:
32
src/plugins/database.ts
Normal file
32
src/plugins/database.ts
Normal file
@@ -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<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' });
|
||||||
Reference in New Issue
Block a user