-
slug를 이용해서 category search 하기Project using Nest.js/E-commerce App 2021. 9. 4. 08:36
개요
Slug는 web 주소의 고유 식별 부분이다. 보통 URL의 끝부분이다. 내 주소에서는 baseURL(clownhacker.tistory.com/)의 뒷 부분인 번호다. 카테고리에 있는 품목 리스트를 출력하기 위해서 카테고리 slug 값이 필요하다. 카테고리 slug 값은 카테고리 name을 processed 한 것이다.
categories.service.ts
async createCategory({ name, coverImg, }: CreateCategoryInput): Promise<CreateCategoryOutput> { try { const categoryName = name.trim().toLowerCase(); const categorySlug = categoryName.replace(/ /g, '-'); const category = await this.categories.findOne({ slug: categorySlug, }); if (category) { return { ok: false, error: '이미 해당 카테고리를 추가하셨습니다.', }; } await this.categories.save( this.categories.create({ name: categoryName, coverImg, slug: categorySlug, }), ); return { ok: true, }; } catch (error) { console.error(error); return { ok: false, error: '카테고리를 추가할 수 없습니다.', }; } }
category를 생성할 때 예를 들어 카테고리 이름을 ' Grocery and Electronics '라고 해보자. 이 때 양 옆에 공백을 trim()으로 지우고 모든 문자를 lowercase로 바꾼다. 이렇게 이름을 가공하고 모든 띄어쓰기를 '-'로 교체하면 slug 값이 완성된다.
Github link
Create create-category resolver : https://github.com/zpskek/houpang-backend-v1/commit/a91b4815ccdd58c08315da74569b5bcb8e68b693
'Project using Nest.js > E-commerce App' 카테고리의 다른 글
NestJS Custom repository (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