git ssb

0+

Piet / ssb-loomio



Tree: 6730668ae7223a39f319ed33a69019c0ef1d8c38

Files: 6730668ae7223a39f319ed33a69019c0ef1d8c38 / poll / async / get.js

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

Built with git-ssb-web