-
NestJS Custom repositoryProject using Nest.js/E-commerce App 2021. 9. 4. 08:47
개요
TypeORM의 Custom Repository를 이용해서 Active Recorder에 없는 method를 추가할 것이다.
categories/repositories/category.repository.ts
import { EntityRepository, Repository } from 'typeorm'; import { Category } from '../entities/category.entity'; @EntityRepository(Category) export class CategoryRepository extends Repository<Category> { async findOneBySlugUsingName(name: string) { const categoryName = name.trim().toLowerCase(); const slug = categoryName.replace(/ /g, '-'); const category = await this.findOne({ slug }); if (!category) { return undefined; } return category; } }
Category라는 Entity를 생성하고 위와 같이 함수를 짜준다. 내가 만든 method는 findOneBySlugUsingName이다. 이 method를 사용하고 싶다면
products.module.ts
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { CategoryRepository } from 'src/categories/repositories/category.repository'; import { Product } from './entities/product'; import { ProductsResolver } from './products.resolver'; import { ProductsService } from './products.service'; @Module({ imports: [TypeOrmModule.forFeature([Product, CategoryRepository])], providers: [ProductsResolver, ProductsService], }) export class ProductsModule {}
imports에 Category가 아닌 CategoryRepository를 추가하자.
products.service.ts
@Injectable() export class ProductsService { constructor( @InjectRepository(Product) private readonly products: Repository<Product>, private readonly categories: CategoryRepository, ) {} }
그리고 service에 private readonly categories : CategoryRepository를 추가하자.
Github link
- Custom Repository : https://typeorm.io/#/many-to-one-one-to-many-relations
'Project using Nest.js > E-commerce App' 카테고리의 다른 글
slug를 이용해서 category search 하기 (0) 2021.09.04 TypeORM의 @ManyToOne과 @OneToMany (0) 2021.09.03 nestJS에서 DTO에서 쓰는 PartialType and PickType을 같이 쓸 때 주의할 점 (0) 2021.09.03 nestJS password security (0) 2021.09.03 nest.js authGuard and authUser decorator (0) 2021.09.02