UNPKG

1.36 kBJavaScriptView Raw
1'use strict';
2var u = require('./util')
3var explain = require('explain-error')
4
5function isFunction (f) {
6 return 'function' === typeof f
7}
8
9function isObject (o) {
10 return o && 'object' === typeof o
11}
12
13function noop (err) {
14 if (err) throw explain(err, 'callback not provided')
15}
16
17//add all the api methods to the emitter recursively
18function recurse (obj, manifest, path, remoteCall) {
19 for(var name in manifest) (function (name, type) {
20 var _path = path ? path.concat(name) : [name]
21 obj[name] =
22 isObject(type)
23 ? recurse({}, type, _path, remoteCall)
24 : function () {
25 return remoteCall(type, _path, [].slice.call(arguments))
26 }
27 })(name, manifest[name])
28 return obj
29}
30
31
32module.exports = function (obj, manifest, _remoteCall, bootstrap) {
33
34 obj = obj || {}
35
36 function remoteCall(type, name, args) {
37 var cb = isFunction (args[args.length - 1]) ? args.pop() : noop
38 var value
39
40 try { value = _remoteCall(type, name, args, cb) }
41 catch(err) { return u.errorAsStreamOrCb(type, err, cb)}
42
43 return value
44 }
45
46
47 if (bootstrap) {
48 remoteCall('async', 'manifest', [function (err, remote) {
49 if(err)
50 return bootstrap(err)
51 recurse(obj, remote, null, remoteCall)
52 bootstrap(null, remote, obj)
53 }])
54 } else {
55 recurse(obj, manifest, null, remoteCall)
56 }
57
58 return obj
59}
60