프로그래밍/Node.js

Node.js 생활코딩 정리 - CRUD + Auth MYSQL 버전 라우트 복잡도 낮추기

가카리 2016. 12. 18. 12:36
반응형

CRUD + Auth MYSQL버전 라우트 복잡도 낮추기

 

이번에는 라우트의 복잡도를 낮추는 작업을 해보자. (업로드 기능은 삭제함)

 

topic에 관련된 라우트는 topic.js로 다 옮김

 

app_mysql2.js

 

var express = require('express');//익스프레스를 가져옴

var bodyParser = require('body-parser')

var app = express();

 

app.use(bodyParser.urlencoded({ extended: false }));//body parser 사용함

app.locals.pretty = true;//템플릿 줄바꿈

app.set('views', './views/mysql');//템플릿 폴더 위치 표시

app.set('view engine', 'jade');//템플릿 엔진을 jade 명시함

app.use('/user', express.static('uploads'));//여기로 폴더에 있는 그림을 접근할 있음

 

var topic = require('./routes/mysql/topic')();

app.use('/topic', topic);// topic으로 들어오면 topic이라는 객체에 위임함

 

app.listen(3003, function(){

console.log('Connected, 3003 port!');

})

 

 

/routes/mysql/topic.js

 

module.exports = function(){

 

var route = require('express').Router();

var conn = require('../../config/mysql/db')();

 

//글작성하기

//new에서 add 바꿈

route.get('/add', function(req, res){

var sql = 'SELECT id, title FROM topic';//글목록을 보여주기 위한 쿼리문

conn.query(sql, function(err, topics, fields){

if(err){//에러가 있다면 여기서 처리

res.status(500).send('Internal Server Error');

}

res.render('topic/add', {topics:topics});

});

});

 

route.get(['/:id/edit'], function(req, res){

var sql = 'SELECT id, title FROM topic';//글목록을 보여주기 위한 쿼리문

conn.query(sql, function(err, topics, fields){

var id = req.params.id;//:id값을 가져옴

if(id){//id 있으면 상세보기

var sql = 'SELECT * FROM topic WHERE id=?';

conn.query(sql, [id], function(err, topic, fields){

if(err){//데이터베이스 에러가 있다면

console.log(err);

res.status(500).send('Internal Server Error');

}else{

res.render('topic/edit', {topics:topics, topic:topic[0]});//topic 쿼리문의 데이터 한개만 넘겨줌

}

});

}else{//id값이 없다면 에러출력

console.log('There is no id.');

res.staus(500).send('Internal server error');

}

});

});

 

route.post(['/:id/edit'], function(req, res){

var title = req.body.title;

var description = req.body.description;

var author = req.body.author;

var id = req.params.id;

var sql = 'UPDATE topic SET title=?, description=?, author=? WHERE id=?';

conn.query(sql, [title, description, author, id], function(err, result, fields){

if(err){

console.log(err);

res.status(500).send('Internal Server Error');

}else{

//res.send(result);//이걸로 먼저 result값을 보고서 해야한다.

res.redirect('/topic/'+id);//변경후 이동 시켜라

}

});

});

 

route.get('/:id/delete', function(req, res){

var sql = 'SELECT id, title FROM topic';//글목록을 보여주기 위한 쿼리문

var id = req.params.id;

conn.query(sql, function(err, topics, fields){

var sql = 'SELECT * FROM topic WHERE id=?';

conn.query(sql, [id], function(err, topic){

if(err){//에러가 있다면 여기서 처리

res.status(500).send('Internal Server Error');

}else{

if(topic.length === 0){

console.log('There is no record.');

res.status(500).send('Internal Server Error');

}

// res.send(topic);//먼저 값을 보자

res.render('topic/delete', {topics:topics, topic:topic[0]});

}

});

});

});

 

route.post('/:id/delete', function(req, res){

var id = req.params.id;

var sql = 'DELETE FROM topic WHERE id=?';

conn.query(sql, [id], function(err, result){

res.redirect('/topic/');//삭제되면 초기화면으로감

});

});

 

 

//폼에서 작성한 것을 여기서 받음

route.post('/add', function(req, res){

var title = req.body.title;//제목과 본문의 내용을 가져옴

var description = req.body.description;

var author = req.body.author;

var sql = 'INSERT INTO topic(title, description, author) VALUES(?, ?, ?)';

 

//쿼리문을 실행한다.

conn.query(sql, [title, description, author], function(err, result, fields){

if(err){//에러가 있다면 여기서 처리

res.status(500).send('Internal Server Error');

}

res.redirect('/topic/'+result.insertId);//insertId 입력한 행의 id값을 의미함

});

 

});

 

//글목록을 표시 mysql 버전

//[] 배열을 의미 둘다 여기로 접근 가능하다는

route.get(['/', '/:id'], function(req, res){

var sql = 'SELECT id, title FROM topic';//글목록을 보여주기 위한 쿼리문

conn.query(sql, function(err, topics, fields){

var id = req.params.id;//:id값을 가져옴

if(id){//id 있으면 상세보기

var sql = 'SELECT * FROM topic WHERE id=?';

conn.query(sql, [id], function(err, topic, fields){

if(err){//데이터베이스 에러가 있다면

console.log(err);

res.status(500).send('Internal Server Error');

}else{

res.render('topic/view', {topics:topics, topic:topic[0]});//topic 쿼리문의 데이터 한개만 넘겨줌

}

});

}else{//첫화면을 보여줌

res.render('topic/view', {topics:topics});//view.jade파일을 출력함 쿼리문에서 가져온 값을 넘겨줌

}

});

});

 

return route;

}

/config/mysql/db.js

 

module.exports = function(){

var mysql = require('mysql');

var conn = mysql.createConnection({

host : 'localhost',

user : 'root',

password : 'qwer1234',

database : 'o2',

port : 3307

});

conn.connect();

return conn;

};

 

실행 화면

이전과 실행 화면은 동일하다.

 

클릭하면 잘된다

 

add를 눌렀을 때

edit를 눌렀을 때

 

delete를 눌렀을 때

 

 

 

출처 : https://opentutorials.org/course/2136

반응형