forked from roa-2019/mealPoll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
63 lines (48 loc) · 1.29 KB
/
routes.js
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
const express = require('express')
const router = express.Router()
const data = require('./data.json')
const fs = require('fs')
module.exports = router
router.get('/', (req, res) => {
res.render('home')
})
router.get('/poll', (req, res) => {
res.render('poll', data)
})
router.post('/poll', (req, res) => {
var keys = Object.keys(req.body)
for (let i = 0; i < data.meals.length; i++) {
var chosenMeal = keys.find(key => key == data.meals[i].name)
if (chosenMeal) {
var voters = data.meals[i].voters
var asVoted = voters.find(voter => voter == req.body.name)
if(!asVoted) {
voters.push(req.body.name)
}
}
}
fs.writeFile('./data.json', JSON.stringify(data), function (err) {
if (err) {
return res.status(500).send('An Error Occured!')
}
res.render('results', data)
})
})
//--------------
//Results Page
//--------------
router.get('/results', (req, res) => {
res.render('results', data)
})
router.post('/results', (req, res) => {
console.log('it works!')
for (let i = 0; i < data.meals.length; i++) {
data.meals[i].voters = [];
}
fs.writeFile('./data.json', JSON.stringify(data), function (err) {
if (err) {
return res.status(500).send('An Error Occured!')
}
res.render('results', data)
})
})