MySQL2 로 DB와 연동하고 promise, async 활용하기

2022. 4. 30. 15:39Web & Server/수업 내용

우선 npm install mysql2 를 해주어야 사용할 수 있다.

mysql2 모듈의 createPool(dbConf) 를 통해

특정 데이터베이스와 커넥션이 되었다.

 

dbConf의 database 항목에는 

MySQL 워크벤치에서 Create 된 Schema의 이름이 들어가야 한다.

 

서버가 클라이언트로부터 요청 받을 때

async함수로 요청이 들어가고 promise 객체가 생긴다.

그 객체 안에서 쿼리를 요청하고 결과를 await한다.

try 안에 포함시킴으로써 catch에서 에러를 잡을 수 있다.

 

서버단 코드

const express = require("express");
const mysql = require("mysql2");
const app = express();

const dbConf = {
  host: "localhost",
  user: "root",
  database: "test",
  password: "123456",
};

const pool = mysql.createPool(dbConf);

app.use(express.json());

app.get("/members", async (req, res) => {
  const promisePool = pool.promise();
  const [rows, fields] = await promisePool.query("select * from members");
  res.send(rows);
});

app.post("/members", async (req, res) => {
  const { email, password, name } = req.body;
  const promisePool = pool.promise();
  try {
    const [rows, fields] = await promisePool.query(
      "insert into members values(?, ?, ?)",
      [email, password, name]
    );
    if (rows.affectedRows > 0) {
      res.send({ status: 200 });
    }
  } catch (err) {
    res.send({ status: err.errno });
  }
});

app.post("/requestFriend", async (req, res) => {
  const { fromEmail, toEmail } = req.body;
  console.log(fromEmail, toEmail);
  const promisePool = pool.promise();

  const q = `select insert_request_friend(?, ?) as result`;
  const [rows, fields] = await promisePool.query(q, [fromEmail, toEmail]);
  console.log(rows[0]);
  if (rows[0].result == 0) {
    //실패
    res.send({ status: 600, message: "이미 친구 요청을 했습니다." });
  } else {
    //성공
    res.send({ status: 200, message: "친구 요청을 했습니다." });
  }
});

const port = 3000;
app.listen(port, () => {
  console.log(`서버가 시작 되었습니다 port: ${port}`);
});

데이터베이스 코드

use test;
show tables;
select * from members where email = 'hong@gmail.com';
insert into members values ('hong@gmail.com', 'asd123', '홍길동');
insert into members values ('lim@gmail.com', 'dsa123', '임꺽정');

select * from members;

## hong@gmail.com -> lim@gmail.com
select * from request_friend;

insert into request_friend values ('hong@gmail.com', 'lim@gmail.com');


delimiter //
create function insert_request_friend($from_email varchar(50), $to_email varchar(50)) returns tinyint
	begin
		declare _count int;
        declare _result tinyint;
		select count(*) into _count from request_friend 
		where $from_email = 'hong@gmail.com' 
		and $to_email = 'lim@gmail.com';
        
        if _count = 0 then
			insert into request_friend values ($from_email, $to_email);
            set _result = 1;
        else 
			set _result = 0;
        end if;
        
        return _result;
        
    end //
delimiter ;



select insert_request_friend('hong@gmail.com', 'lim@gmail.com') as result;


select * from request_friend;
delete from request_friend;