Files: e9238520ce96e4b6ad803bf181a65eb9d888feb4 / obs / get.js
1493 bytesRaw
1 | const { Struct, Value, Array: MutantArray, Dict } = require('mutant') |
2 | const { isBlob } = require('ssb-ref') |
3 | |
4 | function Book (key) { |
5 | return Struct({ |
6 | key, |
7 | value: Value(), |
8 | latestAttributes: Dict(), // attributes according to each user |
9 | errors: MutantArray (), |
10 | sync: false |
11 | }) |
12 | } |
13 | |
14 | module.exports = function (server) { |
15 | return function (key) { |
16 | |
17 | // TODO take key or msg? |
18 | |
19 | const book = Book(key) |
20 | server.get(key, (err, msgVal) => { |
21 | if (err) return book.errors.push(err) |
22 | |
23 | // TODO run isBook? |
24 | book.value.set(msgVal) |
25 | updateLatestAttributes(book, msgVal) |
26 | |
27 | // TODO figure out where to put this |
28 | book.sync.set(true) |
29 | }) |
30 | |
31 | return book |
32 | } |
33 | } |
34 | |
35 | function updateLatestAttributes (book, msgVal) { |
36 | // TODO check isBook / isBookUpdate? |
37 | const { author: user, content } = msgVal |
38 | |
39 | prune(content) |
40 | normalizeImages(content) |
41 | |
42 | const currentAttributes = book.latestAttributes.get(user) || {} |
43 | const latestAttributes = Object.assign({}, currentAttributes, content) |
44 | |
45 | book.latestAttributes.put(user, latestAttributes) |
46 | } |
47 | |
48 | function prune (content) { |
49 | // prune attributes we don't want in the final attributes |
50 | delete content.type |
51 | delete content.about |
52 | } |
53 | |
54 | function normalizeImages (content) { |
55 | if (!content.image) return |
56 | |
57 | var blob |
58 | if (typeof content.image === 'string') blob = content.image |
59 | if (content.image && content.image.link) blob = content.image.link |
60 | |
61 | if (!isBlob(blob)) return delete content.image |
62 | |
63 | content.image = blob |
64 | } |
65 |
Built with git-ssb-web