git ssb

2+

Dominic / ssb-client



Tree: 07198b454eadad3109f5692b847cb5c3b4679a41

Files: 07198b454eadad3109f5692b847cb5c3b4679a41 / index.js

2356 bytesRaw
1var pull = require('pull-stream')
2var muxrpc = require('muxrpc')
3var address = require('ssb-address')
4var ws = require('pull-ws-server')
5var Serializer = require('pull-serializer')
6var loadManf = require('ssb-manifest/load')
7var ssbFeed = require('secure-scuttlebutt/feed')
8var ssbDefaults = require('secure-scuttlebutt/defaults')
9
10function isFunction (f) {
11 return 'function' === typeof f
12}
13
14function throwIfError(err) {
15 if(err) throw err
16}
17
18module.exports = function (config) {
19 var manifest
20 //if we are in the browser
21 config = config || {}
22 config.host = config.host || 'localhost'
23
24 var client = muxrpc(loadManf(config), { auth: 'async' }, serialize)({
25 auth: function (req, cb) {
26 // when this connects to a server, the server auths
27 // back to see who this is. we don't have any apis
28 // for the server to call (yet) so this doesn't do anything.
29 // however, if we don't just let this go through, the server
30 // log shows a nasty error log.
31 cb()
32 }
33 })
34
35 var wsStream
36 var rpcStream
37
38 client.connect = function(addr, cb) {
39 if(isFunction(addr))
40 cb = addr, addr = null
41
42 addr = address(addr || config)
43 client.addr = addr
44 if (wsStream) {
45 wsStream.close()
46 client._emit('reconnecting')
47 }
48
49 var called = false
50 wsStream = ws.connect(addr, {
51 onOpen: function() {
52 client._emit('connect')
53 if(called) return
54 called = true; cb && cb()
55 },
56 onClose: function() {
57 client._emit('close')
58 //rpcStream will detect close on it's own.
59 if(called) return
60 called = true; cb && cb()
61 }
62 })
63
64 rpcStream = client.createStream()
65 pull(wsStream, rpcStream, wsStream)
66
67 return client
68 }
69
70 client.close = function(cb) {
71 wsStream.close()
72 rpcStream.close(cb ? cb : throwIfError)
73 return client
74 }
75
76 client.reconnect = function(opts) {
77 opts = opts || {}
78 client.close(function() {
79 if (opts.wait)
80 setTimeout(client.connect.bind(client, client.addr), opts.wait)
81 else
82 client.connect(client.addr)
83 })
84 return client
85 }
86
87 client.createFeed = function (keys) {
88 return ssbFeed(this, keys, ssbDefaults)
89 }
90
91 return client
92}
93
94function serialize (stream) {
95 return Serializer(stream, JSON, {split: '\n\n'})
96}
97

Built with git-ssb-web