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