git ssb

30+

cel / git-ssb-web



Tree: ec85a9bb2357cf69aed9d9dd3e32d7ba6bcc66f2

Files: ec85a9bb2357cf69aed9d9dd3e32d7ba6bcc66f2 / lib / votes.js

1415 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 downvoters: 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 if (err) return cb(err)
27 cb(null, result)
28 // keep the result updated
29 opts.live = true
30 opts.gte = Date.now()
31 pull(
32 sbot.links(opts),
33 pull.drain(processMsg, function (err) {
34 if (err) console.error('votes', err)
35 })
36 )
37 })
38 )
39
40 function processMsg(msg) {
41 if (!msg || !msg.value) return
42 if (msg.sync) return cb(null, result)
43 var vote = ((msg.value.content || 0).vote || 0).value
44 var author = msg.value.author
45
46 // remove old vote, if any
47 if (author in upvoters) {
48 result.upvotes--
49 delete result.upvoters[author]
50 } else if (author in downvoters) {
51 result.downvotes--
52 delete result.downvoters[author]
53 }
54
55 // add new vote
56 if (vote > 0) {
57 result.upvoters[author] = vote
58 result.upvotes++
59 } else if (vote < 0) {
60 result.downvoters[author] = vote
61 result.downvotes++
62 }
63 }
64}
65

Built with git-ssb-web