-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
93 lines (82 loc) · 2.23 KB
/
index.js
File metadata and controls
93 lines (82 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const express = require('express');
const bodyParser = require('body-parser');
const connect = require('./dbconfig/database');
const QuestionModel = require('./dbconfig/Question');
const Answer = require('./dbconfig/Answer');
const app = express();
//connect to database
connect.authenticate().then(()=>{
console.log("Connection OK")
}).catch((err)=>{
console.log(err);
});
//setting EJS as the view engine
app.set('view engine', 'ejs');
app.use(express.static('public'));
//body parser
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
//routes
app.get('/', (req,res)=>{
QuestionModel.findAll({raw: true, order:[['id','DESC']]}).then((questions) => {
res.render('index', {
questions: questions
});
});
});
app.get('/ask', (req,res)=>{
res.render('ask');
});
app.post('/save', (req,res)=>{
let title = req.body.title;
let description = req.body.description;
//insert into questions
QuestionModel.create({
title: title,
description: description
}).then(()=>{
res.redirect("/");
}).catch((err)=>{
console.log(err);
});
});
app.get('/question/:id', (req,res)=>{
let id = req.params.id;
QuestionModel.findOne({
where:{
id:id
}
}).then(question=>{
if(question != undefined){
Answer.findAll({
where: {
questionId: question.id
},order:[['id', 'DESC']]
}).then(answers=>{
res.render('question', {
question: question,
answers: answers
});
})
}else{
res.send("/");
}
}).catch(err=>{
throw new Error("Query not executed");
})
});
app.post('/answer/:questionId', (req,res)=>{
let body = req.body.body;
let questionId = req.params.questionId;
Answer.create({
body:body,
questionId:questionId
}).then(()=>{
res.redirect(`/question/${questionId}`);
}).catch(err=>{
console.log(err);
});
});
app.listen(3000,()=>{
console.log('App Running');
});