import type { FastifyInstance } from 'fastify'; import fp from 'fastify-plugin'; import { Kysely } from 'kysely'; import { createDatabaseDialect, type DatabaseConfig } from '@/db/config.js'; import type { Database } from '@/db/types.js'; declare module 'fastify' { interface FastifyInstance { db: Kysely; } } export type KyselyPluginOptions = DatabaseConfig; /** * Kysely plugin generates an OpenAPI spec and hosts a UI for browsing and trying the API */ async function _kyselyPlugin(fastify: FastifyInstance, options: KyselyPluginOptions) { const dialect = createDatabaseDialect(options); const db = new Kysely({ dialect, }); fastify.decorate('db', db); fastify.addHook('onClose', async (instance) => { await instance.db.destroy(); instance.log.info('Database connection closed'); }); } export const kyselyPlugin = fp(_kyselyPlugin, { name: 'kysely' });