Skip to content

Instantly share code, notes, and snippets.

@etyp
Created July 23, 2017 23:19
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 etyp/ea8fde66429c4e046c2771c49a02d79c to your computer and use it in GitHub Desktop.
Save etyp/ea8fde66429c4e046c2771c49a02d79c to your computer and use it in GitHub Desktop.
import { Meteor } from 'meteor/meteor';
const methodHooks = {};
const registerMethodHook = (methodNames, position, fn) => {
if (!(methodNames instanceof Array)) {
methodNames = [methodNames];
}
for (let i = 0; i < methodNames.length; i++) {
const methodName = methodNames[i];
if (methodHooks[methodName] == null) {
methodHooks[methodName] = {
before: [],
after: []
};
}
methodHooks[methodName][position].unshift(fn);
}
};
Meteor.beforeMethods = function (methodName, fn) {
return registerMethodHook(methodName, 'before', fn);
};
Meteor.afterMethods = function (methodName, fn) {
return registerMethodHook(methodName, 'after', fn);
};
const wrap = function ({ beforeHook, afterHook, method, methodName }) {
return function () {
const args = Array.prototype.slice.call(arguments);
this._methodName = methodName;
if (beforeHook) {
beforeHook.apply(this, args);
}
const result = method.apply(this, args);
if (afterHook) {
afterHook.apply(this, args);
}
return result;
}
};
Meteor.startup(function() {
for (let method in methodHooks) {
const hooks = methodHooks[method];
let wrappedMethod = Meteor.server.method_handlers[method];
for (let i = 0; i < hooks.before.length; i++) {
const beforeHook = hooks.before[i];
wrappedMethod = wrap({ beforeHook, method: wrappedMethod, methodName: method });
}
for (let j = 0; j < hooks.after.length; j++) {
const afterHook = hooks.after[j];
wrappedMethod = wrap({ afterHook, method: wrappedMethod, methodName: method });
}
Meteor.server.method_handlers[method] = wrappedMethod;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment