Files: fbf36ab9f3e81a1c5b6e0b4c6eed51005e6e07ab / lib / votes.js
1142 bytesRaw
1 | var pull = require('pull-stream') |
2 | var asyncMemo = require('asyncmemo') |
3 | |
4 | module.exports = function (sbot) { |
5 | return asyncMemo(getVotes, sbot) |
6 | } |
7 | |
8 | function 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 | pull( |
18 | sbot.links({dest: id, rel: 'vote', values: true, live: true}), |
19 | pull.drain(processMsg, function (err) { |
20 | if (err) console.error('vote', err) |
21 | }) |
22 | ) |
23 | |
24 | function processMsg(msg) { |
25 | if (!msg) return |
26 | if (msg.sync) return cb(null, result) |
27 | if (!msg.value) return |
28 | var vote = ((msg.value.content || 0).vote || 0).value |
29 | var author = msg.value.author |
30 | |
31 | // remove old vote, if any |
32 | if (author in upvoters) { |
33 | result.upvotes-- |
34 | delete result.upvoters[author] |
35 | } else if (author in downvoters) { |
36 | result.downvotes-- |
37 | delete result.downvoters[author] |
38 | } |
39 | |
40 | // add new vote |
41 | if (vote > 0) { |
42 | result.upvoters[author] = vote |
43 | result.upvotes++ |
44 | } else if (vote < 0) { |
45 | result.downvoters[author] = vote |
46 | result.downvotes++ |
47 | } |
48 | } |
49 | } |
50 |
Built with git-ssb-web