forked from michael-karpinski/voting-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
88 lines (75 loc) · 2.37 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
var express = require('express');
var app = express();
var mongo = require('mongodb').MongoClient;
var bodyParser = require('body-parser');
var url = process.env.DB_URI;
var pkg = require('./package.json');
var path = require('path');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Express only serves static assets in production
// because in dev we use webpack server
// use dotenv module to set NODE_ENV
//if (process.env.NODE_ENV === 'production') {
// comment this line in development as in development
// your webpack server is serving files
app.use(express.static('client/build'));
//}
app.get('/api/polls', (req, res) => {
mongo.connect(url, function(err, db) {
if(err) throw err;
db.collection('polls').find({}).toArray(function(err, docs){
res.end(JSON.stringify(docs));
});
});
});
app.get('/api/poll/:name', (req, res) => {
mongo.connect(url, function(err, db){
if(err) throw err;
db.collection('polls').findOne({"name": req.params.name}, function(err, doc){
res.end(JSON.stringify(doc));
});
});
});
app.post('/api/newpoll', (req, res) => {
mongo.connect(url, function(err,db){
if(err) throw err;
var name = req.body.name;
var options = req.body.option.filter(opt => opt !== '').map(opt => {return {name: opt, votes: 0}});
db.collection('polls').insert({name: name, options: options}, function(err, doc){
res.redirect(pkg.client + '/poll/' + encodeURIComponent(doc.ops[0].name));
});
})
});
app.get('/api/addvote/:name/:option', (req, res) => {
var option = req.params.option;
mongo.connect(url, function(err, db){
if(err) throw err;
db.collection('polls').update(
{name : req.params.name, "options.name":req.params.option},
{$inc: {"options.$.votes": 1}},
(err, doc) => {
if(err) throw err;
db.collection('polls').findOne({name: req.params.name}, (e, d) => {
if(e) throw e;
res.end(JSON.stringify(d));
})
}
)
});
});
app.get('/api/delete/:name', (req, res) => {
var name = req.params.name;
mongo.connect(url, function(err, db){
if(err) throw err;
db.collection('polls').remove({name: name}, function(err, doc){
if(err) throw err;
res.end(JSON.stringify(doc))
});
});
});
// uncomment the below for development environment
// app.get('/*', function (req, res) {
// res.sendFile(path.join(__dirname, './client/build', 'index.html'));
// });
app.listen(3001);