पाठ 23 / 32

Fastify के साथ TypeORM

Data source connection संभालने वाले plugin से TypeORM को Fastify के साथ integrate करें।

TypeORM क्यों?

TypeORM type-safe queries, migrations, और relations provide करता है। एक robust, scalable backend के लिए इसे Fastify के साथ जोड़ें।

TypeORM setup करना

Data source को initialize करें और connection को manage करने के लिए plugin बनाएँ।

import { DataSource } from 'typeorm';
import { User } from './entities/User.js';

const AppDataSource = new DataSource({
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  database: 'mydb',
  entities: [User],
  synchronize: true,
});

export default async function typeormPlugin(fastify) {
  await AppDataSource.initialize();
  fastify.decorate('db', AppDataSource);
  
  fastify.addHook('onClose', () => AppDataSource.destroy());
}