-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatistic.handler.js
110 lines (110 loc) · 3.19 KB
/
statistic.handler.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
var
sys=require('sys'),
couchdb = require('couchdb'),
client = couchdb.createClient(80, 'podviaznikov.cloudant.com'),
db = client.db('quizzer-stat'),
savedStandings='',
savedPosition=0;
exports.getStat=function(userId,callback)
{
db.getDoc(userId, function(er, doc)
{
if(er)
{
//do nothing
}
else
{
sys.log(sys.inspect(doc));
callback(doc);
}
});
}
exports.updateStat=function(userId,run,points,socket,userDisplayName)
{
db.getDoc(userId, function(er, doc)
{
if (er)
{
var stat={answers:1,points:1,seria:1,loginDate:new Date(),userDisplayName:userDisplayName};
db.saveDoc(userId,stat, function(er, ok)
{
if (er)
{
sys.log(JSON.stringify(er));
throw new Error(JSON.stringify(er));
}
sys.puts('Saved '+sys.inspect(stat)+' to the couch');
socket.send(JSON.stringify(stat));
exports.getStandings(function(standings)
{
socket.broadcast(standings);
socket.send(standings);
});
exports.getPosition(userId,function(position)
{
socket.send(position);
});
});
}
else
{
var seria=doc.seria>run?doc.seria:run;
var stat={answers:doc.answers+1,_rev:doc._rev,points:doc.points+points,seria:seria,userDisplayName:userDisplayName};
db.saveDoc(userId,stat, function(er, ok)
{
if (er)
{
sys.log(JSON.stringify(er));
throw new Error(JSON.stringify(er));
}
sys.puts('Saved '+sys.inspect(stat)+' to the couch');
});
socket.send(JSON.stringify(stat));
exports.getStandings(function(standings)
{
socket.broadcast(standings);
socket.send(standings);
});
exports.getPosition(userId,function(position)
{
socket.send(position);
});
}
});
}
exports.getStandings=function(callback)
{
db.view('statistic','standings',{descending:true,limit:10}, function(er, doc)
{
if (er)
{
sys.log(JSON.stringify(er));
throw new Error(JSON.stringify(er));
}
var standings = JSON.stringify({standings:doc.rows});
if(standings!=savedStandings)
{
savedStandings=standings;
}
callback(standings);
});
}
exports.getPosition=function(userId,callback)
{
db.view('statistic','positions',{key:userId}, function(er, doc)
{
if (er)
{
sys.log(JSON.stringify(er));
throw new Error(JSON.stringify(er));
}
var position = JSON.stringify({position:doc.rows[0].value});
sys.log(userId+' has position '+position);
if(position!=savedPosition)
{
savedPosition=position;
callback(position);
}
});
}