Implementación del Patrón Repository en NestJS con TypeORM
Clase 11 de 36 • Curso de NestJS: Persistencia de Datos con TypeORM
Resumen
// src/products/services/products.service.ts
import { InjectRepository } from '@nestjs/typeorm'; // 👈 import
import { Repository } from 'typeorm'; // 👈 import
import { Product } from './../entities/product.entity'; // 👈 entity
import { CreateProductDto, UpdateProductDto } from './../dtos/products.dtos';
@Injectable()
export class ProductsService {
constructor(
@InjectRepository(Product) private productRepo: Repository, // 👈 Inject
) {}
findAll() {
return this.productRepo.find(); // 👈 use repo
}
findOne(id: number) {
const product = this.productRepo.findOne(id); // 👈 use repo
if (!product) {
throw new NotFoundException(`Product #${id} not found`);
}
return product;
}
...
}
// src/users/services/users.service.ts
async getOrderByUser(id: number) {
const user = this.findOne(id);
return {
date: new Date(),
user,
products: await this.productsService.findAll(),
};
}
// src/database/database.module.ts
@Global()
@Module({
imports: [
TypeOrmModule.forRootAsync({
inject: [config.KEY],
useFactory: (configService: ConfigType<typeof config>) => {
const { user, host, dbName, password, port } = configService.postgres;
return {
type: 'postgres',
host,
port,
username: user,
password,
database: dbName,
synchronize: true, // 👈 new attr
autoLoadEntities: true, // 👈 new attr
};
},
}),
],
...
})
export class DatabaseModule {}