MySql에 테이블&데이터생성과 API구현

YU NA Joe·2022년 8월 11일
0

테이블을 만들자

use foodplacesmap; 
CREATE TABLE IF NOT EXISTS FOODMAP (
	IDX int not null auto_increment,
    title varchar(45) not null, 
    address varchar(200) not null, 
    videourl text not null, 
    category varchar(45) not null, 
    createdAt timestamp not null default current_timestamp, 
    updatedAt timestamp not null default current_timestamp, 
    status char(1) not null default 'A', 
    primary key (idx)  
);

데이터를 넣자

INSERT INTO FOODMAP (title, address, videourl, category) VALUES (        '승리돼지국밥'        ,        '경남 창원시 진해구 진해대로 640'        ,        'https://www.youtube.com/watch?v=VP2APbEQ9zo'        ,        '한식'        )        ,
(        '85번실내포장마차'        ,        '경남 진주시 동진로 208-1'        ,        'https://www.youtube.com/watch?v=hzNaa4F-8Z8'        ,        '한식'        )        ,
(        '싱싱식육식당'        ,        '경남 창원시 마산회원구 구암북12길 49'        ,        'https://www.youtube.com/watch?v=sZQpLZpnTbM'        ,        '구이'        )        ,
(        '한우리'        ,        '경남 창원시 마산합포구 문화북1길 61'        ,        'https://www.youtube.com/watch?v=2VdQR4lx1H4'        ,        '한식'        )        ,
(        '바다실비식당'        ,        '경남 창원시 마산회원구 내서읍 상곡로 34'        ,        'https://www.youtube.com/watch?v=KJmy77Koef8'        ,        '회/초밥'        )        ,
(        '뚝방슈퍼'        ,        '경기도 고양시 덕양구 강매로 110-37'        ,        'https://www.youtube.com/watch?v=URxAj91PYDQ'        ,        '한식'        )        ,
(        '할머니집'        ,        '서울특별시 중구 명동3길 42'        ,        'https://www.youtube.com/watch?v=-Kgf9xVdsH8'        ,        '한식'        )        ,
(        '즉석우동짜장'        ,        '서울 영등포구 대방천로 260'        ,        'https://www.youtube.com/watch?v=E1urm6ZhhbY&t=2s'        ,        '중식'        )        ,
(        '스마일하우스'        ,        '경기도 광명시 오리로857번길 6-8'        ,        'https://www.youtube.com/watch?v=tC_7zIl7V2E'        ,        '양식'        )        ,
(        '동흥관'        ,        '서울 금천구 시흥대로63길 20'        ,        'https://www.youtube.com/watch?v=5b1x83ERVK4'        ,        '중식'        )        ,
(        '수저가 간짜장전문점'        ,        '서울특별시 용산구 한강대로 260'        ,        'https://www.youtube.com/watch?v=0nkldoLx0mE'        ,        '중식'        )        ,
(        '병천순대국'        ,        '서울특별시 용산구 원효로58길 31'        ,        'https://www.youtube.com/watch?v=hTWI-MPGgJs'        ,        '한식'        )  ,
(        '희락돈까스'        ,        '서울 영등포구 양산로 210'        ,        'https://www.youtube.com/watch?v=V32AHntBOBs'        ,        '양식'        )        ,
(        '라임하우스'        ,        '경기 광명시 오리로 887'        ,        'https://www.youtube.com/watch?v=JRW7mnmwlIw'        ,        '양식'        )        ,
(        '냠냠물고기'        ,        '서울 송파구 송파대로30길 41-21'        ,        'https://www.youtube.com/watch?v=3J98MLveRlI'        ,        '회/초밥'        )        ,
(        '아카사카'        ,        '서울 서초구 서초대로74길 23'        ,        'https://www.youtube.com/watch?v=5YeceyCzGx4'        ,        '회/초밥'        ) ;

API 만들어보기

indexRoute.js

   // 식당 목록 조회 
   app.get("/foodplaces", index.ReadFoodplaces)

indexController.js

exports.ReadFoodplaces = async function (req, res) {
    const {category} = req.query;
    try {
      const connection = await pool.getConnection(async (conn) => conn);
      try {        
        const [rows] = await indexDao.SelectFoodPlaces(connection, category);
  
        return res.send({
          result: rows,
          isSuccess: true,
          code: 200, // 요청 실패시 400번대 코드
          message: "식당 목록 요청 성공",
        });
      } catch (err) {
        logger.error(`ReadPlaces Query error\n: ${JSON.stringify(err)}`);
        return false;
      } finally {
        connection.release();
      }
    } catch (err) {
      logger.error(`ReadPlaces Connection error\n: ${JSON.stringify(err)}`);
      return false;
    }
  };

indexDao.js

exports.SelectFoodPlaces = async function (connection,category) {
    const SelectAllQuery = `SELECT title, address, videourl, category FROM foodmap;`;
    const SelectCategoryQuery = `SELECT title, address, videourl, category FROM foodmap where category="?";`;
    const Params = [category]; 
    // 카테고리 argus가 들어오면은 cateogory 쿼리를 아니면 모든 rows를 return
    const Query = category ? SelectCategoryQuery : SelectAllQuery;     
    const rows = await connection.query(Query); 
    return rows;
  }; 

전체 장소 조회하기

category 인자를 줘서 조회하기 (한식)

category 인자를 줘서 조회하기 (한식)

유효하지 않은 인자를 줘서 조회해보기

Validation를 주자

indexController.js

exports.ReadFoodplaces = async function (req, res) {
    const {category} = req.query;

    // category에 값이 넘어 왔다면, 유효한 값인지 확인
    if (category) {
        const validCategory = [
            "한식",
            "중식",
            "일식",
            "양식",
            "분식",
            "구이",
            "회/초밥",
            "기타",
        ]; 
        
        if (!validCategory.includes(category)){
                return res.send({                     
                    isSuccess: false, 
                    code: 400, 
                    message: "유효한 카테고리 값이 아닙니당", 
            });    
       }
    } 
    try {
      const connection = await pool.getConnection(async (conn) => conn);
      try {        
        const [rows] = await indexDao.SelectFoodPlaces(connection, category);
  
        return res.send({
          result: rows,
          isSuccess: true,
          code: 200, // 요청 실패시 400번대 코드
          message: "식당 목록 요청 성공",
        });
      } catch (err) {
        logger.error(`ReadPlaces Query error\n: ${JSON.stringify(err)}`);
        return false;
      } finally {
        connection.release();
      }
    } catch (err) {
      logger.error(`ReadPlaces Connection error\n: ${JSON.stringify(err)}`);
      return false;
    }
  };
  

유효하지 않은 인자를 줘서 조회해보기

0개의 댓글