-
Notifications
You must be signed in to change notification settings - Fork 1
/
routes.js
112 lines (74 loc) · 2.14 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
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
111
112
/**
* This file defines the routes used in your application
* It requires the database module that we wrote previously.
*/
var db = require('./database'),
photos = db.photos,
users = db.users;
module.exports = function(app){
// Homepage
app.get('/', function(req, res){
// Find all photos
photos.find({}, function(err, all_photos){
// Find the current user
users.find({ip: req.ip}, function(err, u){
var voted_on = [];
if(u.length == 1){
voted_on = u[0].votes;
}
// Find which photos the user hasn't still voted on
var not_voted_on = all_photos.filter(function(photo){
return voted_on.indexOf(photo._id) == -1;
});
var image_to_show = null;
if(not_voted_on.length > 0){
// Choose a random image from the array
image_to_show = not_voted_on[Math.floor(Math.random()*not_voted_on.length)];
}
res.render('home', { photo: image_to_show });
});
});
});
app.get('/standings', function(req, res){
photos.find({}, function(err, all_photos){
// Sort the photos
all_photos.sort(function(p1, p2){
return (p2.likes - p2.dislikes) - (p1.likes - p1.dislikes);
});
// Render the standings template and pass the photos
res.render('standings', { standings: all_photos });
});
});
// This is executed before the next two post requests
app.post('*', function(req, res, next){
// Register the user in the database by ip address
users.insert({
ip: req.ip,
votes: []
}, function(){
// Continue with the other routes
next();
});
});
app.post('/notcute', vote);
app.post('/cute', vote);
function vote(req, res){
// Which field to increment, depending on the path
var what = {
'/notcute': {dislikes:1},
'/cute': {likes:1}
};
// Find the photo, increment the vote counter and mark that the user has voted on it.
photos.find({ name: req.body.photo }, function(err, found){
if(found.length == 1){
photos.update(found[0], {$inc : what[req.path]});
users.update({ip: req.ip}, { $addToSet: { votes: found[0]._id}}, function(){
res.redirect('../');
});
}
else{
res.redirect('../');
}
});
}
};