현재위치 근처에 있는 모텔 찾기

유신·2020년 12월 24일
0
post-thumbnail

참고자료
https://docs.ncloud.com/ko/api/api-2-1.html Geolocation 이란?
https://apidocs.ncloud.com/ko/ai-application-service/geolocation/geolocation/

나타내는 값:
ip를 통해 현재 위치를 받아 온 뒤, 현재 위치와 관련된 모텔들을 검색하여
모텔에 대한 가격, 이미지, 모텔명을 보여주는 쿼리문을 만들었습니다.

테이블
정규화를 하기 위해 지역 테이블 하위 지역 테이블 동네 테이블을 따로 만들었습니다.
상품 동네선정 테이블을 만들어 상품과 지역을 연결했습니다.

필수 모듈
const requestIp = require('request-ip');
const axios = require('axios');
const CryptoJS = require("crypto-js");
const requestMethod = "GET";
const hostName = 'https://geolocation.apigw.ntruss.com'
const requestUrl= '/geolocation/v2/geoLocation'
const access_key = '각자 본인들의 access_key'
const secret_key = '각자 본인들의 secret_key'

-----------------------------
exports.recentMotel = async function(req,res){
    let ip = req.clientIp;  //클라이언트 ip를 저장할 변수
    let a ={}
    if (ip.length>18){
        ip = ip.substr(7, 22); //ipv6 일경우 ipv4 로 변경 
    }
  
        
        const sortedSet = {};
        sortedSet["ip"] = "ip_address" //ip값 입력 되는곳 ip입력  
        sortedSet["ext"] = "t";
        sortedSet["responseFormatType"] = "json";
      
        let queryString = Object.keys(sortedSet).reduce( (prev, curr)=>{
          return prev + curr + '=' + sortedSet[curr] + '&';
        }, "");
      
        queryString = queryString.substr(0, queryString.length -1 );
      
        const baseString = requestUrl + "?" + queryString;
        const signature = makeSignature(secret_key, requestMethod, baseString, timeStamp, access_key);
      
        const config = {
          headers: {
            'x-ncp-apigw-timestamp': timeStamp,
            'x-ncp-iam-access-key' : access_key,
            'x-ncp-apigw-signature-v2': signature
          }
        }

        try{

             a = await axios.get(`${hostName}${baseString}`, config)
      
        }
        catch(err){
                console.error(err);
        }
        
         

          
        function makeSignature(secretKey, method, baseString, timestamp, accessKey) {
            const space = " ";
            const newLine = "\n";
            let hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secretKey);

            hmac.update(method);
            hmac.update(space);
            hmac.update(baseString);
            hmac.update(newLine);
            hmac.update(timestamp);
            hmac.update(newLine);
            hmac.update(accessKey);
            const hash = hmac.finalize();

            return hash.toString(CryptoJS.enc.Base64);
        }
        
        let data ={
            sub_title:a.data.geoLocation.r2,
            sub_sub_title:a.data.geoLocation.r3
        } 
      


        try{
            const connection = await pool.getConnection(async conn=>conn); // sql연결
            try{        
                try{

                    const list =await productTypeDao.getRecentMotel(data.sub_title,data.sub_sub_title)  //근처 모텔값 가져오기 밑에 DAO 쿼리문도 같이 업로드 했습니다.!
                    // 상품 번호, 상품명 , 대표이미지 , 평점 , 리뷰작성 수 
                    let idList = list.map((item=>item.id)); //상품 아이디 값 배열
                    //주말숙박 가격 평일 숙박가격
                    const priceList = await productTypeDao.getPrice(idList); 상품 아이디값 배열로 상품에 해당하는 가격 가져오기 
                    
                    
           

                    const daycheck = new Date(); //현재날짜 체크하기위해 Date 변수생성
                    if(daycheck == 5 || daycheck == 6){ //5,6 금요일 토요일 주말일경우 주말가격 넣기
                        for(let i=0 ; i< list.length; i++){
                            list[i].price = priceList[i]. weekend_sleep_price
                        }
                    }
                    else { //평일이면 평일 가격 넣기
                        for(let i=0 ; i< list.length; i++){
                            list[i].price = priceList[i]. weekday_sleep_price
                        }
                    }
              
                    res.json({data:a.data.geoLocation.r3,list:list});
                }catch(err){
                    console.error("err",err);
                    connection.release();
                    return false;
               
                }                          
            }
            catch(err){
            logger.error(`example non transaction Query error 2번째\n: ${JSON.stringify(err)}`);
            connection.release();
            return false;
            }
        }
        catch(err){
            console.error("err"+err);
            return false;
        }

}
//상품명, 상품 타이틀 , 상품이미지, 평점, 후기카운트 가져오기
async function getRecentMotel(sub_title,sub_sub_title){
    const connection = await pool.getConnection(async conn => conn);
    const query = `
    select 
    p.id,
	p.product_title ,
	pi2.image_url ,
	(round(sum(prs.review_a +prs.review_b +prs.review_c +prs.review_d )/4/count(prs.review_number ),2)) as score,
	count(prs.review_number ) as num
	from
		product p 
	inner join 
		product_image pi2 
	on 
		p.id = pi2.product_number 
	AND 
		pi2.room_number = 0
	inner join 
		map_product mp 
	on 
		p.id = mp.product_number 
	inner join 
		entire_map em 
	on 
		mp.map_number = em.id 
	inner join 
		sub_map sm 
	on 
		mp.submap_number  = sm.id 
	inner join 
		sub_sub_map ssm 
	on 
		ssm.id  = mp.sub_sub_map_number 
	left outer join 
			product_review pr 
	on 
		p.id  = pr.product_number 
	left outer join 
		product_review_score prs 
	on 
		pr.id  = prs.review_number 
		
	where 
		sm.title  like '%${sub_title}%' or ssm.title like '%${sub_sub_title}%'
	group by p.id ,pi2.image_url 
	
    `

   const [list] = await connection.query(query)
   connection.release();
   return list;
} 

/// 가격 값 가져오기
async function getPrice(idList){
    const connection = await pool.getConnection(async conn => conn);
    const query = `
    

	select 
    pp.product_number ,
    pp.weekday_sleep_price ,
    pp.weekend_sleep_price 
from 
product_price pp 
where  pp.product_number  in(${idList})
and pp.room_number = 1
	
    `

   const [list] = await connection.query(query)
   connection.release();
   return list;
} 

profile
초보개발자

0개의 댓글