git ssb

0+

Piet / ssb-loomio



Tree: f368010bd5cd7dd957193a674e18bd6e6cad8233

Files: f368010bd5cd7dd957193a674e18bd6e6cad8233 / poll / async / get.js

2121 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 msgs
62 .filter(msg => msg.value.content.root === poll.key)
63 .forEach(position => {
64 if (isPosition[type](position)) {
65 // TODO validator checks right position shape, but needs to add e.g. acceptible position ranges based on poll
66 poll.positions.push(position)
67 return
68 }
69
70 if (isPosition(position)) {
71 poll.errors.push({
72 type: ERROR_POSITION_TYPE,
73 message: `Position responses need to be off the ${type} type for this poll`,
74 position
75 })
76 }
77 })
78
79 poll.results = results({ poll, positions: poll.positions })
80
81 return poll
82}
83

Built with git-ssb-web