Skip to content

Instantly share code, notes, and snippets.

@niemyjski
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niemyjski/e0bb970cc5ea59a28a79 to your computer and use it in GitHub Desktop.
Save niemyjski/e0bb970cc5ea59a28a79 to your computer and use it in GitHub Desktop.
JavaScript/TypeScript plugin pipeline
function plugin1(context, next) {
console.log('plugin1');
console.log(context.event);
next();
}
function plugin2(context, next) {
console.log('plugin2');
someIO(next);
}
function plugin3(context, next) {
console.log('plugin3');
context.refid = '123';
next();
}
function badplugin(context, next) {
throw new Error('Blake');
}
function someIO(next) {
console.log('IO');
next();
}
var util = util || {};
util.CallChain = function() {
var cs = [];
this.add = function(call) {
if (call)
cs.push(call);
};
this.execute = function(context) {
var wrap = function (call, next) {
return function () {
try {
call(context, next);
} catch (ex) {
// log to the exceptionless client logger
console.log(ex);
}
};
};
for (var i = cs.length-1; i > -1; i--) {
cs[i] =
wrap(
cs[i],
i < cs.length - 1
? cs[i + 1]
: null);
}
cs[0]();
};
};
var chain = new util.CallChain();
chain.add(plugin1);
chain.add(null);
chain.add(plugin2);
chain.add(plugin3);
//chain.add(badplugin);
chain.add(function(context, next) {
console.log('enqueue event');
console.log(context.event);
if (next) next();
});
var ctx = { 'event': { 'stuff': 'hi' } };
chain.execute(ctx);
console.log('done');
console.log(ctx);
export class Pipeline<Type, Context> {
private _actions = [];
public add(action:(context:Context, next?:() => void) => void): void {
if (action) {
this._actions.push(action);
}
}
public run(context:Context): void {
var wrap = function (action:(context:Context, next?:() => void) => void, next?:() => void) {
return function () {
try {
action(context, next);
} catch (ex) {
console.log(ex);
}
};
};
for (var index = this._actions.length - 1; index > -1; index--) {
this._actions[index] = wrap(
this._actions[index],
index < this._actions.length - 1 ? this._actions[index + 1] : null
);
}
this._actions[0]();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment