Files: 4ed249632b78e458d4fe98521e6f0995546bff38 / index.js
2514 bytesRaw
1 | const { each, map } = require('libnested') |
2 | const onceTrue = require('mutant/once-true') |
3 | const watch = require('mutant/watch') |
4 | const Value = require('mutant/value') |
5 | const assert = require('assert') |
6 | const Defer = require('pull-defer').source |
7 | |
8 | // auto-inject the ssb-server to all methods to reduce repitition |
9 | module.exports = function inject (server, methods, pluginDeps = []) { |
10 | checkMethods(methods) |
11 | |
12 | switch (typeof server) { |
13 | case 'object': // just a classic ssb server |
14 | checkPlugins(server, pluginDeps) |
15 | return map(methods, (fn, path) => fn(server)) |
16 | |
17 | case 'function': // hopefully an observeable which will contain an ssb server |
18 | return injectObsServer(server, methods) |
19 | |
20 | default: |
21 | throw new Error('scuttle-poll expects an ssb server (or obs that contains one)') |
22 | } |
23 | } |
24 | |
25 | function injectObsServer (server, methods, pluginDeps = []) { |
26 | onceTrue(server, server => checkPlugins(server, pluginDeps)) |
27 | |
28 | return map(methods, (fn, path) => { |
29 | if (path.includes('async')) { |
30 | return function () { |
31 | onceTrue( |
32 | server, |
33 | server => fn(server).apply(null, arguments) |
34 | ) |
35 | } |
36 | } |
37 | |
38 | if (path.includes('pull')) { |
39 | return function () { |
40 | const source = Defer() |
41 | onceTrue( |
42 | server, |
43 | server => { |
44 | var _source = fn(server).apply(null, arguments) |
45 | source.resolve(_source) |
46 | } |
47 | ) |
48 | return source |
49 | } |
50 | } |
51 | |
52 | // NOTE - both `obs` and `sync` methods will return observeables |
53 | return function () { |
54 | var result = Value({}) |
55 | // var result = Struct({}) // WARNING - this shouldn't be copied for other apps, only works with obs.get method here. Probably breaks sync.isBlog |
56 | onceTrue( |
57 | server, |
58 | server => { |
59 | var res = fn(server).apply(null, arguments) |
60 | watch(res, res => result.set(res)) |
61 | } |
62 | ) |
63 | return result |
64 | } |
65 | }) |
66 | } |
67 | |
68 | function checkMethods (methods) { |
69 | const server = { backlinks: 'fake' } |
70 | each(methods, (fn, path) => { |
71 | assert(typeof fn === 'function', `${path.join('.')}: expect each method to be a function`) |
72 | const injectedMethod = fn(server) |
73 | assert(typeof injectedMethod === 'function', `${path.join('.')}: expect each method to be a closure which accepts a server and returns a function`) |
74 | }) |
75 | } |
76 | |
77 | function checkPlugins (server, pluginDeps) { |
78 | pluginDeps.forEach(p => { |
79 | if (!server[p]) throw new Error(`scuttle-blog needs a scuttlebot server with the ${p} plugin installed`) |
80 | }) |
81 | } |
82 |
Built with git-ssb-web