git ssb

0+

Piet / ssb-loomio



Tree: 468d684bfde5b5b265ab076477d4c4930e4d8dc8

Files: 468d684bfde5b5b265ab076477d4c4930e4d8dc8 / poll / async / get.js

2022 bytesRaw
1const pull = require('pull-stream')
2const sort = require('ssb-sort')
3const isPoll = require('../../isPoll')
4const isPosition = require('../../isPosition')
5const { ERROR_POSITION_TYPE } = require('../../types')
6const results = require('../../position/sync/chooseOneResults')
7
8module.exports = function (server) {
9 return function get (key, cb) {
10 server.get(key, (err, value) => {
11 if (err) return cb(err)
12
13 var poll = { key, value }
14 if (!isPoll(poll)) return cb(new Error('scuttle-poll could not fetch, key provided was not a valid poll key'))
15
16 pull(
17 createBacklinkStream(key),
18 pull.collect((err, msgs) => {
19 if (err) return cb(err)
20
21 cb(null, decoratedPoll(poll, msgs))
22 })
23 )
24 })
25 }
26
27 function createBacklinkStream (key) {
28 var filterQuery = {
29 $filter: {
30 dest: key
31 }
32 }
33
34 return server.backlinks.read({
35 query: [filterQuery],
36 index: 'DTA' // use asserted timestamps
37 })
38 }
39}
40
41function decoratedPoll (rawPoll, msgs = []) {
42 const { author, content: { title, body } } = rawPoll.value
43
44 const poll = Object.assign({}, rawPoll, {
45 author,
46 title,
47 body,
48
49 positions: [],
50 results: {},
51 errors: []
52
53 // publishPosition: TODO ? add pre-filled helper functions to the poll?
54 })
55
56 // TODO add missingContext warnings to each msg
57 msgs = sort(msgs)
58
59 // filter position message into 'positions' and 'errors'
60 const type = poll.value.content.pollDetails.type
61
62 poll.positions = msgs
63 .filter(msg => msg.value.content.root === poll.key)
64 .filter(isPosition[type])
65
66 poll.errors = msgs
67 .filter(msg => msg.value.content.root === poll.key)
68 .filter(msg => isPosition(msg) && !isPosition[type](msg))
69 .map(position => {
70 return {
71 type: ERROR_POSITION_TYPE,
72 message: `Position responses need to be off the ${type} type for this poll`,
73 position
74 }
75 })
76
77 poll.results = results({ poll, positions: poll.positions })
78
79 return poll
80}
81

Built with git-ssb-web