Files: 66945405e614808df83374c5ee2b994ef5782b9a / wrap.js
1838 bytesRaw
1 | var PullCont = require('pull-cont') |
2 | var pull = require('pull-stream') |
3 | |
4 | module.exports = function wrap(sv, since, isReady) { |
5 | var waiting = [] |
6 | |
7 | var meta = {} |
8 | |
9 | sv.since(function (upto) { |
10 | if(!isReady.value) return |
11 | while(waiting.length && waiting[0].seq <= upto) |
12 | waiting.shift().cb() |
13 | }) |
14 | |
15 | isReady(function (ready) { |
16 | if(!ready) return |
17 | var upto = sv.since.value |
18 | if(upto == undefined) return |
19 | while(waiting.length && waiting[0].seq <= upto) |
20 | waiting.shift().cb() |
21 | }) |
22 | |
23 | function ready (cb) { |
24 | if(isReady.value && since.value != null && since.value === sv.since.value) cb() |
25 | else |
26 | since.once(function (upto) { |
27 | if(isReady.value && upto === sv.since.value) cb() |
28 | else waiting.push({seq: upto, cb: cb}) |
29 | }) |
30 | } |
31 | |
32 | var wrapper = { |
33 | source: function (fn, name) { |
34 | return function (opts) { |
35 | meta[name] ++ |
36 | return pull(PullCont(function (cb) { |
37 | ready(function () { cb(null, fn(opts)) }) |
38 | }), pull.through(function () { meta[name] ++ })) |
39 | } |
40 | }, |
41 | async: function (fn, name) { |
42 | return function (opts, cb) { |
43 | meta[name] ++ |
44 | ready(function () { |
45 | fn(opts, cb) |
46 | }) |
47 | } |
48 | }, |
49 | sync: function (fn, name) { |
50 | //return function (a, b) { |
51 | //meta[name] ++ |
52 | return fn//(a, b) |
53 | //} |
54 | } |
55 | } |
56 | |
57 | var o = {ready: ready, since: sv.since, close: sv.close, meta: meta} |
58 | if(!sv.methods) throw new Error('a stream view must have methods property') |
59 | |
60 | for(var key in sv.methods) { |
61 | var type = sv.methods[key] |
62 | var fn = sv[key] |
63 | if(typeof fn !== 'function') throw new Error('expected function named:'+key+'of type: '+type) |
64 | //type must be either source, async, or sync |
65 | meta[key] = 0 |
66 | o[key] = wrapper[type](fn, key) |
67 | } |
68 | |
69 | o.methods = sv.methods |
70 | |
71 | return o |
72 | } |
73 | |
74 | |
75 | |
76 | |
77 | |
78 | |
79 | |
80 | |
81 |
Built with git-ssb-web