1st Project_day7(1)_11.20

송철진·2022년 11월 20일
0

1st Project

목록 보기
5/13

where절을 만드는 함수를 최적화해서 만들어보자

1. 목표

지난번 짰던 코드에서 불필요한 부분을 제거하거나 리팩토링한다.

  • 불필요한 부분: scent, gender 객체를 별도 선언
    -> 매칭시킬 필요없이 id가 아니라 name컬럼을 선택하면 되는 거였다.
  • 리팩토링할 부분: or 쿼리를 만드는 부분이 반복되므로 따로 함수를 선언해서 밖으로 빼준다

2. 소스코드

( OR )형태의 쿼리를 출력하는 함수

첫번째 인자 arr : array타입, gender 또는 scent
두번째 인자 str : string타입, g.name 또는 sc.name

const orQuery = (str, arr) => {
  if(!arr){
    return "";
  }
  let query = '(';
  for(let i=0; i<arr.length; i++){
    query += `${str} = "${arr[i]}"`;
            
    if(i===(arr.length-1)){
      return query + ')';
    }
        
    query += ' OR ';
  }
}

WHERE ( ) AND ( )형태의 쿼리를 출력하는 함수

인자 arr : array타입, 빈배열이면 ""을 출력

const whereAndQuery = (arr) => {
  let filtered = arr.filter((element) => element !== '');
  if(filtered.length === 0){
    return "";
  }
  let query = `WHERE `;
  for(let i=0; i<filtered.length; i++){
    query += filtered[i];
    if(i===(filtered.length-1)){
       return query;
    }
    query += ' AND ';
  }
}

(po.price >= AND po.price <= )형태의 쿼리를 출력하는 함수

첫번째 인자 lowprice : Number타입, 최저가 이상
두번째 인자 highprice : Number타입, 최고가 이하

const filteredPrice = (lowprice, highprice) => {
  if(!highprice && !lowprice){
    return "";
  }else if(!highprice){
    return `(po.price >= ${lowprice})`
  }else if(!lowprice){
    return `(po.price <= ${highprice})`
  }else{
    return `(po.price >= ${lowprice} AND po.price <= ${highprice})`
  }
}

실행 예)

// 쿼리 파라미터에 담긴 내용
let gender = ["male","female"]
let scent = ["citrus", "fruity"]
let lowprice = 100000
let highprice = 300000

//controllers 레이어
const {gender, scent, lowprice, highprice} = req.query

// services 레이어
let array = [
  orQuery("g.name", gender), 
  orQuery("sc.name", scent), 
  filteredPrice(lowprice, highprice)
]

// where절 확인
console.log(  whereAndQuery(array)  )

3. 보완해야할 점

에러핸들링

  • 클라이언트가 잘못된 변수 명을 불러올 경우?(-> controller 레이어에 구현되어 있음!)
    • 예) scnet=["citrus"] 라고 보냈다면?
    • 예) gendr=["male"] 라고 보냈다면?
  • 클라이언트가 잘못된 변수 값을 불러올 경우?
    • 예) scent=["citurs"] 라고 보냈다면? (철자 순서가 틀림)
      실행결과: 아무것도 표시하지 않음
    • 예) gender=["malee"] 라고 보냈다면? (e를 하나 지워야 함)
      실행결과: 아무것도 표시하지 않음
    • 예) gender=["male", "fe"] 라고 보냈다면? (일부 요소만 맞음)
      실행결과: "male" 관련 정보만 표시

무신사 사이트를 참조했을 때 쿼리 파라미터의 값이 틀렸다고해서
에러를 표시하지 않고 나머지 매칭되는 부분을 보여주는 것을 알 수 있다.
이런 경우에 대한 에러핸들링은 꼭 필요하진 않을지도?

참조: 무신사
1) list_kind = small 일 때
https://www.musinsa.com/categories/item/001004?d_cat_cd=001004&brand=&list_kind=small

2) list_kind = smallx 일 때
https://www.musinsa.com/categories/item/001004?d_cat_cd=001004&brand=&list_kind=smallx

profile
검색하고 기록하며 학습하는 백엔드 개발자

0개의 댓글