이번 시간에는, 해당 html 에서 new 기능이었던, 새로운 글을 추가하는 기능을 구현해볼것이다.
우선, new
로 작성된 코드와 문서들을 모두 add
로 바꿔준다.
(네이밍의 통일성이 필요하다.)
다 수정했다면, 이제 /topic/add 로 접속을 하게되면, 저장된 파일폴더에서 가져오는 것이 아닌, orientdb 에서 가져오도록 수정한다.
app.get('/topic/add', function(req,res){
// topic 이라는 항목에 해당하는 값을 가져온다 라는 sql 문
var sql = "SELECT FROM topic";
db.query(sql).then(function(topics){
// 만약, topics 로 받은 값이 없다면, 해당 코드를 따라간다.
if(topics.length === 0){
console.log('There is no record');
res.status(500).send('Internal Server Error');
}
// 만약, topics 를 제대로 받았다면, add.jade 파일에 콜백함수의 인수인
// topics 를 topics 라고 jade에 전달한다.
res.render('add', {
topics:topics
})
}
})
해당 라우터를 수정해주고, add.jade 파일을 수정해준다.
add.jade 에서 POST 형식으로 /topic/add 로 정보를 서버에 보내줘야하기 때문에 해당 부분을 수정한다.
또한, 새로운 author input 을 추가해준다.
article
form(action='/topic/add' method = 'POST')
p
input(type='test' name ='title' placeholder ='title')
p
textarea(name='description' placeholder ='description')
p
input(type='test' name='author' placeholder='author')
p
input(type='submit')
수정이 끝났다면, 해당 폼으로 작성했을 때 POST 로 받을 /topic/add 라우터에 대한 수정이 필요하다.
app.post('/topic/add', function(req,res){
// req
var title = req.body.title;
var description = req.body.description;
var author = req.body.author;
var sql = "INSERT INTO topic (title, description, author) VALUES(:title,:desc,:author)"
db.query(sql,{
params:{
title:title,
desc:description,
author:author
}
}).then(function(results){
res.redirect('/topic/'+ encodeURIComponent(results[0]['@rid']));
})
})
res.redirect('/topic/'+encodeURIComponent(result[0]['@rid']))
을 통해서, 해당 페이지로 넘어간다.