Careeroza
Repositories
Injecting a Repository
src/products/products.module.ts
@Module({
imports: [TypeOrmModule.forFeature([Product])], // makes Repository<Product> injectable here
controllers: [ProductsController],
providers: [ProductsService],
})
export class ProductsModule {}src/products/products.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from './entities/product.entity';
import { CreateProductDto } from './dto/create-product.dto';
import { UpdateProductDto } from './dto/update-product.dto';
@Injectable()
export class ProductsService {
constructor(@InjectRepository(Product) private readonly repo: Repository<Product>) {}
findAll() {
return this.repo.find({ relations: { category: true }, order: { createdAt: 'DESC' }, take: 20 });
}
async findOne(id: number) {
const product = await this.repo.findOne({ where: { id }, relations: { category: true } });
if (!product) throw new NotFoundException(`Product ${id} not found`);
return product;
}
create(dto: CreateProductDto) {
return this.repo.save(this.repo.create(dto)); // create() builds the entity, save() INSERTs
}
async update(id: number, dto: UpdateProductDto) {
const product = await this.repo.preload({ id, ...dto }); // load + merge
if (!product) throw new NotFoundException(`Product ${id} not found`);
return this.repo.save(product);
}
async remove(id: number) {
const result = await this.repo.delete(id);
if (result.affected === 0) throw new NotFoundException(`Product ${id} not found`);
}
}Common Repository Methods
| Method | SQL idea |
|---|---|
find({ where, order, skip, take, relations }) | SELECT ... WHERE ... ORDER BY ... LIMIT/OFFSET |
findOneBy({ id }) | SELECT ... WHERE id = $1 LIMIT 1 |
findAndCount(...) | Rows + total count (pagination) |
save(entity) | INSERT or UPDATE |
update(id, partial) | UPDATE without loading |
delete(id) / softDelete(id) | DELETE / set deletedAt |
increment({ id }, 'stock', 5) | UPDATE ... SET stock = stock + 5 |
createQueryBuilder('p') | Hand-built complex queries |
// operators for where clauses
import { Between, ILike, In, MoreThan } from 'typeorm';
export const examples = (repo: Repository<Product>) => [
repo.find({ where: { price: Between(1000, 5000), stock: MoreThan(0) } }),
repo.find({ where: { name: ILike('%boat%') } }), // case-insensitive search
repo.findBy({ id: In([1, 7, 9]) }),
repo.createQueryBuilder('p')
.select('p.categoryId', 'categoryId')
.addSelect('COUNT(*)', 'count')
.groupBy('p.categoryId')
.getRawMany(),
];