Collar.js Addon
You can extend collar with addon. Now it supports two extension points:
- observers
- operators
An addon is simply a javascript object with two extension point fields:
module.exports = {
observers: {
// key: observer pairs
},
operators: {
// key: operator pairs
}
}
Usage
Register your addon with Collar.use(addon)
API.
const collar = require('collar.js');
collar.use(myAddon);
Operator
Operator is a function, which returns a node instance.
An example throttle
operator
// first create a node class
class Throttle extends Node {
constructor(options, eventemitter) {
super(options, eventemitter);
this._type = "throttle";
this.ms = options.ms;
this.last = new Date().getTime();
}
onSignal(signal) {
let now = new Date().getTime();
if (now - this.ms >= this.last) {
this.last = now;
this.send(signal);
}
}
}
// next, create operator by initiating the node in a function with arguments
function throttle(ms) {
return new Throttle({
ms,
});
}
// export the addon by putting the operator in operators object
const myAddon = {
operators: {
throttle
}
}
// register it
const collar = require('collar.js');
collar.use(myAddon);
const ns = collar.ns('com.collartechs.test');
// the registered operator accepts the exact number of arguments defined in your operator function
const throttleNode = ns.throttle(100);
Observer
Observer is used to monitoring the signal and node when node is processing signals. An observer is a function:
function observer(when, node, ...) {}
- when: string, the monitoring phase, one of 'send', 'onReceive', 'to'
- node: Node, which node is currently monitoring
According to different monitoring phase, there could be additional arguments. See below:
when node received a signal
function observer(when, node, signal) {}
- when === 'onReceive'
- node: the current node
- signal: the signal to received
when node sends a signal
function observer(when, node, signal) {}
- when === 'send'
- node: the current node
- signal: the signal to be sent
when node connects to another node
function observer(when, node, downstreamNode) {}
- when === 'send'
- node: the current node
- downstreamNode: the node to connect to
Example:
A logger to log all signals send by nodes
module.exports = {
observers: {
logger: function(when, node, signal) {
if (when !== 'send') return;
console.log(node.id, 'send', signal.payload);
}
}
}