git ssb

0+

mixmix / ssb-client-basic-tutorial



Tree: 20f85b8d98278bf1dd978dcd5e2d2ce0ceed922b

Files: 20f85b8d98278bf1dd978dcd5e2d2ce0ceed922b / v04.js

1915 bytesRaw
1const Connection = require('ssb-client')
2const pull = require('pull-stream')
3pull.paraMap = require('pull-paramap')
4const html = require('yo-yo')
5const daysPosts = require('./source/days-posts')
6const getName = require('./async/get-name')
7
8const App = html`
9 <div style="margin: 2rem;">Loading...</div>
10`
11document.body.appendChild(App)
12
13Connection((err, server) => {
14 if (err) throw err
15
16 const today = new Date(2018, 9, 17)
17
18 pull(
19 daysPosts(server)(today),
20 pull.paraMap(addName, 50), // run up to 50 asyncrhonous maps in parallel
21 pull.collect(onDone)
22 )
23
24 function addName (data, cb) {
25 // getName is a much less opinionated method which just takes a feedId and asynchronously calls back with a name
26 // addName is then a function which knows about the shape of the data coming through the stream and how to handle the results
27 getName(server)(data.author, (err, name) => {
28 if (err) cb(err)
29 else {
30 data.authorName = name
31 cb(null, data)
32 }
33 })
34 }
35
36 function onDone (err, data) {
37 if (err) {
38 console.error('oh noes', err)
39 server.close()
40 return
41 }
42
43 const newView = Messages(data)
44 html.update(App, newView)
45
46 console.log(`${data.length} messages`)
47 console.timeEnd('get posts')
48 server.close()
49 }
50})
51
52function Messages (data) {
53 return html`
54 <div style="font-family: arial;">
55 ${data.map(Message)}
56 </div>
57 `
58}
59
60function Message (msgData) {
61 const { authorName, timestamp, text, root } = msgData
62 // this is called 'destructuring' and is equivalent to `const authorName = msgData.authorName` etc
63
64 const thread = root
65 ? html`
66 <p style="font-size: .8rem; margin: 0">thread: ${root}</p>
67 `
68 : null
69
70 return html`
71 <div style="margin: 2rem;">
72 <strong>${authorName}</strong> - ${new Date(timestamp).toLocaleString()}
73 ${thread}
74 <p>${text}</p>
75 </div>
76 `
77}
78

Built with git-ssb-web