const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const Oriento = require('oriento');
const server = Oriento({
host: 'localhost',
port: 2424,
username: 'root',
password: '***'
});
var db = server.use('o2')
console.log('Using database: ' + db.name)
app.use(bodyParser.urlencoded({ extended: false }))
app.locals.pretty = true
app.set('views', './views')
app.set('view engine', 'pug')
app.get('/topic/add', (req, res) => {
res.render('add')
})
app.post('/topic/add', (req, res) => {
const title = req.body.post_title
const name = req.body.post_name
const description = req.body.post_description
const sql = 'INSERT INTO topic (title, author, description) VALUES(:title, :name, :description)'
db.query(sql, {params: {title: title, name: name, description: description}}).then((result) => {
console.log(result)
const id = encodeURIComponent(result['@rid'])
res.redirect('/topic/')
})
})
app.get('/topic/:id/edit', (req, res) => {
const id = decodeURIComponent(req.params.id)
const sql = 'SELECT FROM topic where @rid=:rid'
db.query(sql, {params: {rid: id}}).then((topic) => {
console.log(topic)
res.render('edit', {topic: topic[0]})
})
})
app.post('/topic/:id/edit', (req, res) => {
const rid = decodeURIComponent(req.params.id)
const title = req.body.post_title
const name = req.body.post_name
const description = req.body.post_description
const sql = `UPDATE topic SET title=:title, author=:name,
description=:description WHERE @rid=:rid`
db.query(sql, {
params: {
rid: rid,
title: title,
name: name,
description: description}
}).then((topic) => {
console.log('edit complete')
res.redirect('/topic/' + encodeURIComponent(req.params.id))
})
})
app.get('/topic/:id/delete', (req, res) => {
const rid = decodeURIComponent(req.params.id)
const sql = 'DELETE FROM topic WHERE @rid=:rid'
db.query(sql, {params: {rid: rid}}).then((result) => {
console.log('delete successfully')
res.redirect('/topic/')
})
})
app.get(['/topic', '/topic/:id'], (req, res) => {
const sql = 'SELECT FROM topic'
db.query(sql).then((results) => {
if (req.params.id) {
const id = decodeURIComponent(req.params.id)
const sql2 = 'SELECT FROM topic WHERE @rid=:rid'
db.query(sql2, {params: {rid: id}}).then((topic) => {
console.log(topic)
res.render('topic', {topic: topic[0], topics: results})
})
} else {
res.render('topic', {topic: {title: 'Welcome!', name: 'Master', description: 'Practicing'}, topics: results})
}
})
})
app.listen(3000, () => {
console.log('Server connected at 3000!')
})