Files: 9314ed556aff05392a2a7b5046429b1467c248bb / loader.js
1420 bytesRaw
1 | var fs = require('fs') |
2 | var path = require('path') |
3 | |
4 | var mainPath = path.resolve(__dirname, 'index.js') |
5 | var mtime |
6 | var main |
7 | function loadMain() { |
8 | var stats = fs.statSync(mainPath) |
9 | var prevMtime = mtime |
10 | mtime = stats.mtime.getTime() |
11 | if (mtime !== prevMtime) { |
12 | delete require.cache[mainPath] |
13 | main = require(mainPath) |
14 | var k |
15 | if (main.manifest && exports.manifest) { |
16 | for (k in main.manifest) exports.manifest[k] = main.manifest[k] |
17 | } |
18 | for (k in main) exports[k] = main[k] |
19 | return true |
20 | } |
21 | } |
22 | loadMain() |
23 | |
24 | exports.init = function (sbot, config) { |
25 | var api |
26 | var wsUseHandler |
27 | var wsUse = sbot.ws && sbot.ws.use |
28 | if (wsUse) sbot.ws.use = function (handler) { |
29 | if (!wsUseHandler) wsUseHandler = handler |
30 | else wsUse.call(sbot.ws, handler) |
31 | } |
32 | |
33 | function loadApi() { |
34 | if (loadMain() || !api) { |
35 | var prevApi = api |
36 | var init = typeof main === 'function' ? main : main.init |
37 | wsUseHandler = null |
38 | api = init.call(main, sbot, config) |
39 | } |
40 | } |
41 | |
42 | if (wsUse) wsUse(function (req, res, next) { |
43 | loadApi() |
44 | if (wsUseHandler) wsUseHandler(req, res, next) |
45 | else if (next) next() |
46 | }) |
47 | |
48 | loadApi() |
49 | var wrappedApi = {} |
50 | function wrapMethod(method) { |
51 | return function () { |
52 | loadApi() |
53 | return api[method].apply(api, arguments) |
54 | } |
55 | } |
56 | for (var method in main.manifest || api) { |
57 | wrappedApi[method] = wrapMethod(method) |
58 | } |
59 | return wrappedApi |
60 | } |
61 |
Built with git-ssb-web