Methods Middleware
fork of Konecty Methods Middleware
Add more power to Meteor.methods with methods-middleware
--
With this package you can register methods that will be registered as native Meteor methods, is the same as use Meteor.methods to create methods but using this package you can do more like:
- Register regular methods;
- Register middlewares and only reference them when register methods to be executed before this method;
- Add methods to be executed before and after all your methods registered with registerMethod;
Installation
meteor add sbborders:methods-middleware
Execution Pipeline
- Execute all before methods
- Execute middlewares registered for called method
- Execute called method
- Execute all after methods
If MIDLEWARES or BEFORE METHODS returns something different from UNDEFINED the execution stops and return this value!
Regular Methods
Register a method named sum
1Meteor.registerMethod('sum', function(a, b) { 2 return a + b; 3});
Call registered method sum as normal methods
1Meteor.call('sum', 2, 3);
Methods with Middlewares
Register a new middleware to convert arguments to number and pass to method via context
1Meteor.registerMiddleware('toNumber', function() { 2 var args = Array.prototype.slice.apply(arguments); 3 4 args.forEach(function(arg, index) { 5 args[index] = parseFloat(arg); 6 }); 7 8 this.arguments = args; 9 return 10});
Register a method named sum using the middleware toNumber and get values from context
1Meteor.registerMethod('sum', 'toNumber', function(a, b) { 2 return this.arguments[0] + this.arguments[1]; 3});
Call registered method sum passing strings that will be converted by middleware
1Meteor.call('sum', '2', '3');
Before and After Methods
You can register methods to be executed before and after all methods registered with registerMethod. In the above example we are tracking execution time and logging to console.
This method will be executed before every method call and will put in context the date and time from the begining of the execution
1Meteor.registerBeforeMethod('startTimer', function() { 2 this.startedAt = new Date(); 3 return 4});
This method will be executed after every method call and will get the date time saved in context to calculate the execution time and log to console
1Meteor.registerAfterMethod('endTimer', function(a, b) { 2 var now = new Date(); 3 console.log('Time: ' + (now.getTime() - this.startedAt.getTime())); 4 return 5});