Commit dced1754f5ef610ebc96c986a27362230b599868
Refactor Votes to use a single live stream
cel committed on 10/19/2016, 1:34:33 AMParent: 568953d78d77276b131c221c8c15f5e4af5edbb4
Files changed
lib/votes.js | changed |
lib/votes.js | ||
---|---|---|
@@ -1,39 +1,46 @@ | ||
1 | 1 … | var pull = require('pull-stream') |
2 | 2 … | var asyncMemo = require('asyncmemo') |
3 | 3 … | |
4 | 4 … | module.exports = function (sbot) { |
5 | - return asyncMemo(getVotes, sbot) | |
6 | -} | |
5 … | + var votes = {} | |
7 | 6 … | |
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 | 7 … | pull( |
18 | - sbot.links({dest: id, rel: 'vote', values: true, live: true}), | |
8 … | + sbot.links({rel: 'vote', values: true, old: false}), | |
19 | 9 … | pull.drain(processMsg, function (err) { |
20 | 10 … | if (err) console.error('vote', err) |
21 | 11 … | }) |
22 | 12 … | ) |
23 | 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 … | + | |
24 | 30 … | 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 | |
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 | |
29 | 36 … | var author = msg.value.author |
30 | 37 … | |
31 | 38 … | // remove old vote, if any |
32 | - if (author in upvoters) { | |
39 … | + if (author in result.upvoters) { | |
33 | 40 … | result.upvotes-- |
34 | 41 … | delete result.upvoters[author] |
35 | - } else if (author in downvoters) { | |
42 … | + } else if (author in result.downvoters) { | |
36 | 43 … | result.downvotes-- |
37 | 44 … | delete result.downvoters[author] |
38 | 45 … | } |
39 | 46 … |
Built with git-ssb-web