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