-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmoleculer.js
90 lines (81 loc) · 3.02 KB
/
moleculer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const { ServiceBroker } = require('moleculer');
const util = require('util');
module.exports = async function create({id, socket, channel, logLevel, logger, mapLocal, findMethodIn}) {
if (typeof socket === 'string') {
socket = {transporter: socket};
}
const broker = new ServiceBroker({
namespace: channel,
logLevel,
logger: bindings => ({
trace: (...params) => logger.trace && logger.trace(bindings, util.format(...params)),
debug: (...params) => logger.debug && logger.debug(bindings, util.format(...params)),
info: (...params) => logger.info && logger.info(bindings, util.format(...params)),
warn: (...params) => logger.warn && logger.warn(bindings, util.format(...params)),
error: (...params) => logger.error && logger.error(bindings, util.format(...params)),
fatal: (...params) => logger.fatal && logger.fatal(bindings, util.format(...params))
}),
...socket
});
function brokerMethod(typeName, methodType) {
return function() {
const $meta = (arguments.length > 1 && arguments[arguments.length - 1]) || {};
return broker.call(
'ports.' + $meta.method.split('.').shift() + '.' + methodType,
Array.prototype.slice.call(arguments)
)
.then(res => {
res && delete res.ctx;
return res;
})
.catch(err => {
err && delete err.ctx;
throw err;
});
};
}
function start() {
return broker.start();
}
function stop() {
return broker.stop();
}
function localRegister(nameSpace, name, fn) {
mapLocal[nameSpace + '.' + name] = fn;
}
function exportMethod(methods, namespace, reqrep, port) {
const actions = {};
if (methods instanceof Array) {
methods.forEach(function(fn) {
if (fn instanceof Function && fn.name) {
actions[namespace + '.' + fn.name] = ctx => {
return fn.apply(null, ctx.params);
};
localRegister(namespace, fn.name, fn, reqrep);
}
});
} else {
Object.keys(methods).forEach(function(key) {
if (methods[key] instanceof Function) {
actions[namespace + '.' + key] = ctx => {
return methods[key].apply(methods, ctx.params);
};
localRegister(namespace, key, methods[key].bind(methods), reqrep);
}
});
}
return broker.createService({
name: broker.nodeID + '/' + port + (reqrep ? '' : '-events'),
settings: {
$noServiceNamePrefix: true
},
actions
});
}
return Promise.resolve({
stop,
start,
exportMethod,
brokerMethod
});
};