11.5 Related Products

With·2022년 3월 20일
0

관련항목 기능 구현하기

1. useSWR typing 하기

import { Product, User } from '@prisma/client' // db 테이블의 타입을 prisma에서 생성해준 것을 사용할 수 있음

// product에 user 정보를 포함했기 때문에 별도의 타입이 필요함
// type ProductDetailResponse = { 
//  ok: boolean;
//  product: Product
// }

// interface를 사용할 때는 extneds를 통해 생성함
type ProductWithUser = { 
  ok: boolean;
  product: Product & { user: User }
}

const { data } = useSWR<ProductWithUser>()...;

2. realtedProduct 조회 명령 작성

OR: One or more conditions must return true

// post의 title이 Prisma 이거나 databases이 포함된 것을 조회하여 return 함
// OR에 [ ]을 넣어주면 관련 키워드를 지닌 값을 리턴하도록 응용
const result = await prisma.post.findMany({
  where: {
    OR: [
      {
        title: {
          contains: 'Prisma',
        },
      },
      {
        title: {
          contains: 'databases',
        },
      },
    ],
  },
})

해당 아이템의 이름을 통해 관련 아이템을 조회 할 검색어 키워드를 생성한다. prisma의 filter api를 이용해서 아래와 같은 배열의 형태를 생성한다. 만약 해당 아이템의 이름이 '갤럭시 s60'이라면, split를 이용해서 배열을 생성한다.

// 관련 항목 검색어 추출

const itemName = '갤럭시 s60';
const terms = itemName.split(" ").map(word => ({
  name: {
    contains : {
      word
    }
  }
}))
// [{name: containes: { word: '갤럭시' }}, {name: containes: { word: 's60' }}]

const relatedProducts = client.product.findMany({
  where: {
    OR: terms,
  }
});

// 그리고 생성된 배열을 위와 같이 삽입

조회된 결과물

그리고 이어서, 현재 게시물은 관련 아이템에서 조회되지 않도록 처리한다. OR과 AND를 이용해서 조건을 연결하고, not을 이용해서 ~이 아닌 조건을 설정한다.

const relatedProducts = client.product.findMany({
  where: {
    OR: terms,
    AND: {
      id: {
        not: product?.id,
      }
    }
  }
});
profile
주니어 프론트엔드 개발자 입니다.

0개의 댓글