git ssb

0+

Piet / ssb-loomio



Tree: 9144ab97554ad603dd57ff8d50d81940ac397cc6

Files: 9144ab97554ad603dd57ff8d50d81940ac397cc6 / poll / async / get.js

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

Built with git-ssb-web