Files: 9db352a29a6d5bac4344c081e9228bd03aaeb97c / poll / async / get.js
1828 bytesRaw
1 | const pull = require('pull-stream') |
2 | const sort = require('ssb-sort') |
3 | const isPoll = require('../../isPoll') |
4 | const isPosition = require('../../isPosition') |
5 | const { ERROR_POSITION_TYPE } = require('../../types') |
6 | const results = require('../../position/sync/chooseOneResults') |
7 | |
8 | module.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(msgs => { |
19 | cb(null, decoratedPoll(poll, msgs)) |
20 | }) |
21 | ) |
22 | }) |
23 | } |
24 | |
25 | function createBacklinkStream (key) { |
26 | var filterQuery = { |
27 | $filter: { |
28 | dest: key |
29 | } |
30 | } |
31 | |
32 | return server.backlinks.read({ |
33 | query: [filterQuery], |
34 | index: 'DTA' // use asserted timestamps |
35 | }) |
36 | } |
37 | } |
38 | |
39 | function decoratedPoll (rawPoll, msgs) { |
40 | const { title, body } = rawPoll.value.content |
41 | |
42 | const poll = Object.assign({}, rawPoll, { |
43 | title, |
44 | body, |
45 | |
46 | positions: [], |
47 | results: {}, |
48 | errors: [] |
49 | }) |
50 | |
51 | // filter position message into 'positions' and 'errors' |
52 | // TODO schema checks right position shape, but needs to add e.g. acceptible position ranges based on poll |
53 | // TODO add missingContext warnings |
54 | msgs = sort(msgs) |
55 | const type = poll.value.content.pollDetails.type |
56 | msgs.forEach(msg => { |
57 | if (isPosition[type](msg)) { |
58 | poll.positions.push(msg) |
59 | return |
60 | } |
61 | |
62 | if (isPosition(msg)) { |
63 | poll.errors.push({ |
64 | type: ERROR_POSITION_TYPE, |
65 | message: `Position responses need to be off the ${type} type for this poll`, |
66 | position: msg |
67 | }) |
68 | } |
69 | }) |
70 | |
71 | poll.results = results(poll.positions) |
72 | |
73 | return poll |
74 | } |
75 |
Built with git-ssb-web