-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
110 lines (99 loc) · 2.9 KB
/
Copy pathindex.js
File metadata and controls
110 lines (99 loc) · 2.9 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const express = require('express')
const bodyParser = require('body-parser')
const connection = require('./db/database')
const Pergunta = require('./db/Pergunta')
const Resposta = require('./db/Resposta')
connection
.authenticate()
.then(() => {
console.log('conexão feita')
})
.catch((error) => {
console.log(error)
})
const server = express()
//express usando o EJS como renderizador de HTML
server.set('view engine', 'ejs')
server.use(express.static('public')) //pasta que ficarão arquivos utilizados apenas no front
server.use(bodyParser.urlencoded({ extended: false })) //vai organizar dados de formulário em uma estrutura para o javascript
server.use(bodyParser.json())
server.get('/', (req, res) => {
Pergunta
.findAll({ raw: true, order: [
['id', 'DESC'] //ASC
]} )
.then((perguntas) => {
res.render('index', {perguntas: perguntas})
})
})
server.get('/perguntar', (req, res) => {
res.render('perguntar')
})
server.post('/salvarpergunta', (req, res) => {
const titulo = req.body.titulo
const pergunta = req.body.pergunta
Pergunta
.create({
titulo: titulo || null,
descricao: pergunta || null
})
.then(() => {
res.redirect('/')
})
.catch((error) => {
console.log(`erro ao salvar PERGUNTA: ${error}`)
res.redirect('/')
})
})
server.get('/pergunta/:id', (req, res) => {
const id = req.params.id
Pergunta
.findOne( {
where: {id: id}
})
.then((pergunta) => {
if (pergunta) {
Resposta
.findAll( {
raw: true,
order: [
['id', 'DESC']
],
where: {
perguntaId: id
}
})
.then((respostas) => {
res.render('pergunta', {
pergunta: pergunta,
respostas: respostas
})
})
} else {
res.redirect('/')
}
})
})
server.post('/responder', (req, res) => {
const corpo = req.body.corpo
const perguntaId = req.body.perguntaId
Resposta
.create({
corpo: corpo || null,
perguntaId: perguntaId
})
.then(() => {
res.redirect(`/pergunta/${perguntaId}`)
})
.catch((error) => {
console.log(`erro ao salvar RESPOSTA: ${error}`)
res.redirect(`/pergunta/${perguntaId}`)
})
})
server.listen(3000, (error) => {
if (error) {
console.log(`o ocorreu um (ou mais) erro: ${error}`)
} else {
console.log('servidor iniciado com sucesso!')
}
})