@farewellutopia
Here is an example function to get the latest vote by a user for a target id.
This will use the most efficient RPC API if available, and fall back to others. (TODO: support go-sbot [%7QnBSs0...]) For the sake of simplicity, it uses pull.filter/take/map in all cases, even though that could be omitted or simplified if using the ssb-query or ssb-backlinks method. Public domain.
// Get latest vote by feed for target.
// Calls back:
// > 0 (usually 1): upvote
// 0: unvote (retracted/reset vote)
// null: no vote
// < 0 (usually -1): downvote (rare)
// other: invalid/unknown vote
// Note: vote expression is omitted
function getVote(sbot, feed, target, cb) {
pull(
// most efficient: use ssb-backlinks, returning one message
sbot.backlinks ? sbot.backlinks.read({
reverse: true,
limit: 1,
query: [{$filter: {
dest: target,
value: {
author: feed,
content: {
type: 'vote',
vote: {
link: target
}
}
}
}}]
}) :
// sbot.links: returns all the user's votes for the target.
// usually the user has few votes, so this is okay.
sbot.links ? sbot.links({
source: feed,
dest: target,
rel: 'vote',
values: true,
reverse: true,
}) :
// ssb-query: scan through user's vote messages
sbot.query ? sbot.query.read({
reverse: true,
limit: 1,
query: [{$filter: {
value: {
author: feed,
content: {
type: 'vote',
vote: {
link: target
}
}
}
}}]
}) :
// scan through user's feed
sbot.createUserStream ? sbot.createUserStream({
id: feed,
reverse: true
}) : pull.error('Unable to get votes'),
// verify vote message schema
// needed for use with sbot.links and createUserStream above
pull.filter(function (msg) {
var c = msg && msg.value && msg.value.content
return c && c.type === 'vote'
&& c.vote && c.vote.link === target
}),
pull.take(1),
pull.map(function (msg) {
var c = msg && msg.value && msg.value.content
return c && c.vote && c.vote.value
}),
pull.collect(function (err, msgs) {
if (err) return cb(err)
if (!msgs.length) return cb(null, null)
cb(null, msgs[0])
})
)
}