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