Skip to content

Instantly share code, notes, and snippets.

@pvenkatakrishnan
Last active August 29, 2015 14:16
Show Gist options
  • Save pvenkatakrishnan/58676023eef547b48b18 to your computer and use it in GitHub Desktop.
Save pvenkatakrishnan/58676023eef547b48b18 to your computer and use it in GitHub Desktop.
//the pluginSpec from the instrument module
var plugin = {
name: 'aPLugin',
spec: {
'onTransport': {
'clients' : 'someClient' /*or*/ ['clienta', 'clientb', 'clientc' ...] /*or * if none specified */,
'action': 'exec:./doSomething'
},
'onStats':
{
'clients' : 'someClient' /*or*/ ['clienta', 'clientb', 'clientc' ...] /*or * if none specified */,
'action': 'exec:./doSomethingElse'
}
}
}
//the plugin
module.exports = function Plugin (pluginSpec) {
this.plugin = {};
this.plugin.triggers = {};
Object.keys(pluginSpec).spec.forEach(function(key) {
var clients = pluginSpec.spec[key].clients;
plugin.triggers[key].clients = {};
if(Array.isArray(clients)) {
clients.forEach(function(client) {
plugin.triggers[key].clients[client] = pluginSpec.spec[key].action;
});
} else if (clients === undefined || clients === '*') {
plugin.triggers[key].clients['*'] = pluginSpec.spec[key].action;
} else if(typeof clients === 'string') {
plugin.triggers[key].clients[clients] = pluginSpec[key].action;
}
});
}
Plugin.prototype.run = function(trigger, client, context) {
if (this.plugin.triggers[trigger] && this.plugin.triggers[trigger].clients[client]) {
this.plugin.triggers[trigger].clients[client].apply(null, arguments);
}
}
//the registry
var Registry = function() {
this.plugins = {};
}
Registry.prototype.add = function(pluginSpec) {
Assert.ok(Thing.isString(pluginSpec.name), 'Expected name to be a string.');
Plugins[pluginSpec.name] = new Plugins(pluginSpec);
}
Registry.prototype.remove = function(plugin /*name or spec*/) {
if (typeof plugin !== 'string') {
plugin = plugin.name;
}
delete plugins[plugin];
}
};
Registry.prototype.run = function(trigger, client, context) {
var args = Array.prototype.slice.call(arguments);
this.plugins.forEach(function(p) {
p.run.apply(null, args);
});
}
//usage of registry
servicore.plugins = new Registry();
servicecore.plugins.add(pluginSpec); //can be stashed into a json file the plugin modules
//to run them.
servicecore.plugins.run('onTransport', 'clientName', options);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment