-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
89 lines (72 loc) · 2.41 KB
/
server.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
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
const express = require('express')
const hbs = require('express-handlebars')
const fs = require('fs')
const multer = require('multer')
const server = express()
const cheeseData = require('./cheeseData.json')
const testFunc = require('./functions')
// multer configuration
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
// By default, multer removes file extensions so let's add them back
filename: function (req, file, cb) {
cb(null, Date.now() + file.originalname)
}
})
const upload = multer({ storage: storage })
// middleware
server.use(express.static('public'))
server.use(express.urlencoded({ extended: false }))
// handlebars configuration
server.engine('hbs', hbs({ extname: 'hbs' }))
server.set('view engine', 'hbs')
// routes
server.get('/:title', (req,res) => {
if (req.params.title == "home") {
var viewData = {
title: 'The Grate Cheese Off',
cheeseSelection: cheeseData.cheeseSelection
}
var template = 'home'
} else if (req.params.title == "add") {
var viewData = {
title: 'Cheese Culture Factory',
}
var template = 'add'
}
res.render(template, viewData)
})
server.post('/add', upload.single('cheeseImage'), (req, res)=> {
const newCheeseData = req.body
/*fs.readFile('./cheeseData.json', (err, data) => {
if (err) console.log(err)
const listOCheese = JSON.parse(data).cheeseSelection*/
let cheeseList = [...cheeseData.cheeseSelection]
let newCheeseId = Math.max(...cheeseList.map(el => el.id)) + 1
newCheeseData.id = newCheeseId
newCheeseData.image = req.file.filename
newCheeseData.votes = 0
const newCheeseList = [...cheeseList, newCheeseData]
const newData = {cheeseSelection: newCheeseList}
fs.writeFile('cheeseData.json', JSON.stringify(newData, null, 2), function (err) {
if (err) throw err
})
res.redirect('home')
})
server.post('/home', (req,res) => {
let idx = req.body.id
let arr = cheeseData.cheeseSelection
let newArr = arr.map((el) => {
if (el.id == idx) {
let voteCount = el.votes + 1
el.votes = voteCount
} else { return el }
})
fs.writeFile('cheeseData.json', JSON.stringify({cheeseSelection : arr}, null, 2), function (err) {
if (err) throw err
})
res.redirect('home')
})
module.exports = server