git ssb

0+

mixmix / ssb-client-basic-tutorial



Tree: cf524354e56763eb8ba2d0ab07b1fe49066baec6

Files: cf524354e56763eb8ba2d0ab07b1fe49066baec6 / v02.js

1723 bytesRaw
1const Connection = require('ssb-client')
2const pull = require('pull-stream')
3
4console.log('Connecting')
5
6Connection((err, server) => {
7 if (err) throw err
8 console.log('Connection established')
9
10 const today = new Date()
11 const opts = {
12 reverse: true,
13 query: [
14 {
15 $filter: {
16 value: {
17 content: { type: 'post' },
18 timestamp: {
19 $gte: Number(startOfDay(today)),
20 $lt: Number(startOfDay(today, +1))
21 }
22 }
23 }
24 },
25 {
26 $map: {
27 author: ['value', 'author'],
28 timestamp: ['value', 'timestamp'],
29 text: ['value', 'content', 'text'],
30 root: ['value', 'content', 'root'] // the root messages of a thread, this is present if this post is a reply to another message
31 }
32 }
33 ]
34 }
35
36 pull(
37 server.query.read(opts),
38 pull.collect(onDone)
39 )
40
41 function onDone (err, msgs) {
42 if (err) {
43 console.error('oh noes', err)
44 server.close()
45 return
46 }
47
48 msgs.forEach(msg => {
49 prettyPrint(msg)
50 console.log('------')
51 })
52
53 console.log(`${msgs.length} messages`)
54 server.close()
55 }
56})
57
58// helpers
59
60function startOfDay (time = new Date(), dayOffset = 0) {
61 // dayOffset = 0 means if this argument is not supplied to set it to default to 0
62
63 const year = time.getFullYear()
64 const month = time.getMonth()
65 const date = time.getDate() + dayOffset
66 return new Date(year, month, date, 0, 0, 0) // 0 hours, 0 minutes, 0 secords
67}
68
69function prettyPrint (obj) {
70 console.log(JSON.stringify(obj, null, 2))
71 // this just print the full object out as a string that's been nicely indented
72 // with each level of nesting
73}
74

Built with git-ssb-web