git ssb

30+

cel / git-ssb-web



Tree: 89ce7442bb7d0a3e38e89aab3f493cba4140cba4

Files: 89ce7442bb7d0a3e38e89aab3f493cba4140cba4 / votes.js

1245 bytesRaw
1var pull = require('pull-stream')
2var asyncMemo = require('asyncmemo')
3
4module.exports = function (sbot) {
5 return asyncMemo(getVotes, sbot)
6}
7
8function getVotes(sbot, id, cb) {
9 var upvoters, downvoters
10 var result = {
11 upvoters: upvoters = {},
12 downvotes: downvoters = {},
13 upvotes: 0,
14 downvotes: 0
15 }
16
17 var opts = {
18 dest: id,
19 rel: 'vote',
20 values: true,
21 keys: false
22 }
23 pull(
24 sbot.links(opts),
25 pull.drain(processMsg, function (err) {
26 cb(err, result)
27 // keep the result updated
28 opts.live = true
29 pull(
30 sbot.links(opts),
31 pull.drain(processMsg)
32 )
33 })
34 )
35
36 function processMsg(msg) {
37 if (msg.sync) return cb(null, result)
38 var vote = ((msg.value.content || 0).vote || 0).value
39 var author = msg.value.author
40
41 // remove old vote, if any
42 if (author in upvoters) {
43 result.upvotes--
44 delete result.upvoters[author]
45 } else if (author in downvoters) {
46 result.downvotes--
47 delete result.downvoters[author]
48 }
49
50 // add new vote
51 if (vote > 0) {
52 result.upvoters[author] = vote
53 result.upvotes++
54 } else if (vote < 0) {
55 result.downvoters[author] = vote
56 result.downvotes++
57 }
58 }
59}
60

Built with git-ssb-web