git ssb

6+

Dominic / epidemic-broadcast-trees



Tree: d7274a7dbfa5c6ea2e60d2a7e9e592973469a894

Files: d7274a7dbfa5c6ea2e60d2a7e9e592973469a894 / example.js

1685 bytesRaw
1var pull = require('pull-stream')
2var createEbtStream = require('./')
3var Obv = require('obv')
4//create a datamodel for a reliable chat room.
5
6function createChatModel (id, log) {
7 //in this example, logs can be a map of arrays,
8 var logs = {}
9 if(id) logs[id] = log || []
10
11 var onAppend = Obv()
12 return {
13 logs: logs,
14 append: function append (msg) {
15 (logs[msg.author] = logs[msg.author] || []).push(msg)
16 onAppend.set(msg)
17 },
18 onAppend: onAppend
19 }
20}
21
22function createStream(chat) {
23
24 //so the vector clock can be
25 var vectorClock = {}
26 for(var k in chat.logs)
27 vectorClock[k] = chat.logs[k].length
28
29 //observables are like an event emitter but with a stored value
30 //and only one value per instance (instead of potentially many named events)
31
32
33 var stream = createEbtStream(
34 //pass a get(id, seq, cb)
35 function (id, seq, cb) {
36 if(!chat.logs[id] || !chat.logs[id][seq-1])
37 return cb(new Error('not found'))
38 cb(null, chat.logs[id][seq-1])
39 },
40 //pass append(msg, cb)
41 function (msg, cb) {
42 chat.append(msg)
43 cb()
44 }
45 ) ({
46 seqs: vectorClock,
47 })
48
49 chat.onAppend(stream.onAppend)
50
51 return stream
52}
53
54if(!module.parent) {
55
56 var alice = createChatModel('alice', [])
57 var bob = createChatModel('bob')
58
59 var as = createStream(alice)
60 var bs = createStream(bob)
61
62 pull(as, bs, as)
63
64 //have bob get ready to receive something
65 bob.onAppend(function (msg) {
66 console.log('msg at bob:', msg)
67 })
68
69 //have alice send a message to bob
70 alice.append({author: 'alice', sequence: 1, content: 'hello bob!'})
71
72}
73
74exports.createChatModel = createChatModel
75exports.createStream = createStream
76
77
78
79
80

Built with git-ssb-web