const express = require('express');
const app = express();
var mysql = require('mysql');
var db = mysql.createConnection({
host : "localhost",
user: "root",
password: "1234",
database: "dbtheory_task"
});
db.connect(function(err) {
if (err) throw err;
console.log('DB connected');
});
app.set('view engine', 'ejs');
app.set('views','./views');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', function (req, res) {
var page = parseInt(req.query.page || 1);
var sql = 'select * from post order by postID desc';
db.query(sql, function (err, rows, fields) {
if(err) console.log('select fail...\n' + err);
var howmanyposts = rows.length;
var howmanypages = Math.ceil(howmanyposts / 10);
const posts = rows.slice((page - 1) * 10, (page - 1) * 10 + 10);
res.render('mainpage', { list : posts, thispage: page, howmanypages });
});
});
app.get('/posting', function (req, res) {
res.render('posting.ejs');
});
app.post('/postingL', function (req, res) {
var body = req.body;
var params = [body.title, body.author, body.content];
var sql = 'insert into post(title, author, content, date) values (?, ?, ?, NOW())';
db.query(sql, params, function(err) {
if(err) console.log('insert fail\n' + err);
else res.redirect('/');
});
});
app.get("/post:postID", function (req, res) {
db.query('select * from post where postID = ?', [req.params.postID], function (error, result1) {
var post = result1[0];
db.query('select * from comment where postID = ?', [req.params.postID], function (error, comment) {
res.render('post.ejs', {post, comment});
});
});
});
app.get("/delete:postID", function (req, res) {
db.query('delete from post where postID = ?', [req.params.postID], function (err) {
if(err) console.log('delete fail\n' + err);
res.redirect('/');
});
});
app.post('/commenting:postID', (req, res) => {
var body = req.body;
var params = [req.params.postID, body.content ,body.author];
var sql = 'insert into comment(postID, content, author, date) values (?, ?, ?, NOW())';
db.query(sql, params, function(err) {
if(err) console.log('insert fail\n' + err);
res.redirect('back');
});
});
app.post('/commentdelete:commentID', (req, res) => {
db.query('delete from comment where commentID = ?', [req.params.commentID], function (err) {
if(err) console.log('delete fail\n' + err);
res.redirect('back');
});
});
app.listen(3000);