forked from crtr0/votr-part1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.js
71 lines (60 loc) · 2.25 KB
/
events.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
var config = require('./config')
, utils = require('./utils')
, cradle = require('cradle')
, connection = new(cradle.Connection)(config.couchdb.url, config.couchdb.port, {
auth:{username: config.couchdb.username, password: config.couchdb.password},
cache: true})
, events = connection.database('events')
// query events based on either shortname or phonenumber (both unique keys)
, findBy = exports.findBy = function(attr, val, callback, retries) {
var retries = (typeof retries !== 'undefined') ? retries : 0;
events.view('event/by'+utils.initcap(attr), {key: val}, function (err, res) {
if (err) {
if (retries < 3) {
console.log('Failed to load event, retrying: ' + attr + ', ' + val);
findBy(attr, val, callback, retries+1);
}
else
var msg = 'Failed to load event, DONE retrying: ' + attr + ', ' + val;
console.log(msg);
callback(msg, null);
}
else {
if (res.length != 1) {
var msg = 'No matching event: ' + attr + ', ' + val;
console.log(msg);
callback(msg, null);
}
else {
var event = res[0].value;
callback(null, event);
}
}
});
}
// check to see if this user has voted for this event
, hasVoted = exports.hasVoted = function(event, number) {
var retval = false;
event.voteoptions.forEach(function(vo){
if (vo.numbers.indexOf(number) >= 0) {
retval = true;
}
});
return retval;
}
// persist the vote to the DB
, saveVote = exports.saveVote = function(event, vote, from, callback) {
var index = vote - 1;
event.voteoptions[index].votes++;
event.voteoptions[index].numbers.push(from);
events.save(event._id, event, function(err, res) {
if (err) {
var msg = 'Failed to save vote for event id = ' + event._id + '. ' + JSON.stringify(err);
console.log(msg);
callback(msg, null);
}
else {
callback(null, event.voteoptions[index]);
}
});
};