# डेटाबेस Integration — Fastify

Source: https://www.geekswithgeeks.com/hi/fastify/ff-database-integration

> Fastify routes से डेटाबेस को connect और query करें।

## Database as plugin

Plugin में database connection को initialize करें और routes में उपयोग के लिए Fastify instance को decorate करें।

## डेटाबेस plugin उदाहरण

एक plugin जो Prisma client को setup करता है और routes में उपलब्ध कराता है।

```javascript
import { PrismaClient } from '@prisma/client';

export default async function dbPlugin(fastify, opts) {
  const prisma = new PrismaClient();
  
  fastify.addHook('onClose', async () => {
    await prisma.$disconnect();
  });
  
  fastify.decorate('db', prisma);
}

// In a route:
fastify.get('/users', async () => {
  return await fastify.db.user.findMany();
});
```

## Connection को gracefully handle करें

Fastify shutdown के समय database को disconnect करने के लिए `onClose` hook उपयोग करें।
