Express 가 무엇인지, 그리고 왜 사용하는지에 대해 정리해봤으니
이제 DB를 붙여 (MySQL) 아주 간단한 CRUD API 를 짜보겠다.
프로젝트의 구조는 다음과 같다.
메인 애플리케이션인 index.js,
쿼리를 작성해 DB 에서 데이터를 가져오는 db.js,
그리고 routes 폴더 내 jjigae.js 에서 데이터를 가공할 것 이다.
▶ index.js
//1
const express = require("express"); //express 모듈
const bodyParser = require('body-parser');
const PORT = 3001;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
//2
const jjigaeRouter = require('./routes/jjigae');
app.use('/jjigae',jjigaeRouter);
//3
app.listen(PORT, () => console.log(`Running on port ${PORT}`));
1.
express 에서 body 에서 데이터를 꺼내 쓰려면 body-parser 가 필요하다.
클라이언트에서 HTTP Request 를 통해 요청한 것을
jjigaeRouter 에서 꺼내 쓸 예정이기 때문에
미들웨어에 bodyParser 를 태워(?) 준다.
express 4.16.0 버전부터 body-parser 가 express 에 내장되어
body-parser 모듈을 불러오는 것을 생략하고 아래와 같이 작성할 수 있다.
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
2.
라우팅을 소개하고, 사용한 기록을 이전 포스팅에 작성하긴했었지만
Spring 친화적(?) 으로 다시 설명해보자면
MainController 의 역할을 하는 것이 메인애플리케이션 (index.js) 이다.
index.js 는 어떤 방식으로 처리를 할지 정의하는데, 이때 들어온 요청을 특정 메서드와 매핑하기 위해 라우터를 사용하는 것이다.
라우터가 @RequestMapping 어노테이션과 비슷하게 동작하는 것을 알 수 있다.
/jjigae 로 들어온 요청들은 jjigaeRouter 로 보내겠다고 미들웨어로 명시한다.
3.
마지막으로 앱이 실행되었을 때 어느 포트에서 작동하는지 확인할 수 있는 로그를 띄웠다.
▶ 조회
전체 리스트 조회
db.js
const mysql = require("mysql");
const connection = mysql.createConnection({
host: "{localhost}",
user: "root",
password: "{password}",
database: "Jjigae",
port: "3306",
});
DB 와 서버를 연결하는 객체 createConnection() 에 DB 에 관한 정보를 넣어준다.
function getAllJjigae(callback){
connection.query(`SELECT * FROM JJIGAE`,(err, rows)=>{
if(err) throw err;
callback(rows);
});
}
JJIGAE 테이블의 모든 데이터를 가져오는 메서드이다.
query() 의 기본형태는 다음과 같다.
connection.query(sql, function(error, rows, fields){
}
첫번째 인자로 SQL 구문을 받는다.
콜백의 rows 는 구분에 해당하는 행을,
fields 는 열을 배열 형태로 받는다.
이렇게 DB 받아온 데이터를 callback() 의 인자로 넣어 전달한다.
콜백함수 : 다른 함수의 인자로써 넘겨진 후 특정 이벤트에 의해 호출되는 함수. 이 때 함수는 포인터나 람다식 등으로 전달된다.
jjigae.js
router.get('/',(req,res,next)=>{
db.getAllJjigae((rows)=>{
res.send(rows);
});
});
전달받은 전체 찌개 리스트 데이터를 응답한다.
▶ 조회
조건에 알맞은 데이터 조회
db.js
function getJjigaeByKey(key, value, callback){
connection.query(`SELECT * FROM JJIGAE WHERE ${key}=${value}`,(err, row)=>{
if(err) throw err;
callback(row);
});
}
조건을 id 로 설정한 쿼리문 , name 으로 설정한 쿼리문 2개를 작성해야했는데
쿼리문에 변수를 넣어 getJjigaeByKey() 메서드 하나로 통합했다.
( 중복되는 느낌이라서 한개로 합쳤는데 다시 보니
getJjigaeById , getJjigaeByName 두개 메서드를 만든 것이 명시적이고 더 깔끔했을 것 같다)
jjigae.js
router.get('/:id',(req,res)=>{
const key = 'id';
db.getJjigaeByKey(key, req.params.id, (row)=>{
res.send(row);
});
});
인자로 key 와 value 를 넣어준다.
express 에서 데이터를 서버에 보내는 방법 중 Query Params 방식을 사용했다.
작동방식은 Spring 의 @PathVariable 어노테이션과 동일하다.
@GetMapping("/{id}")
public get_method(@PathVariable("id") int id){
..
};
데이터는 params 에 담겨오기때문에
req.params.{path} 로 값을 가져올 수 있다.
▶ 등록
새로운 객체 등록
db.js
function insertJjigae(object, callback){
connection.query(`INSERT INTO JJIGAE(name, description) VALUES ('${object.name}', '${object.description}')`,(err, result)=>{
if(err) throw err;
callback(result);
});
}
jjigae.js
router.post("/", (req, res) => {
db.insertJjigae(req.body, () => {
res.redirect("/jjigae");
});
});
DB 에 새로운 찌개를 등록하고 /jjigae 경로로 이동
▶ 삭제
조건에 알맞은 데이터 삭제
db.js
function deleteJjigae(id, callback){
connection.query(`DELETE FROM JJIGAE WHERE ID=${id}`, (err, result)=>{
if(err) throw err;
callback();
});
}
jjigae.js
router.delete("/:id", (req, res) => {
const id = req.params.id; //Query Params
db.deleteJjigae(id, () => {
res.redirect("/jjigae");
});
});
▶ 수정
조건에 맞는 데이터 수정
db.js
function updateJjigaeByName(object, callback){
connection.query(`update jjigae set description = '${object.description}' where name = '${object.name}'`,(err)=>{
if(err) throw err;
callback();
});
}
jjigae.js
router.put("/", (req, res) => {
const key = "name";
const value = "'" + req.body.name + "'";
let detailResponse;
db.getJjigaeByKey(key, value, (row) => {
detailResponse = row;
});
if(!detailResponse){
res.send('새로운 객체는 post 요청 ! ');
}
db.updateJjigaeByName(req.body, () => {
res.redirect("/jjigae");
});
});
새로운 객체는 수정이 불가하므로 문자열로 응답
'Express' 카테고리의 다른 글
[Express] Express 개요 (0) | 2022.12.07 |
---|