Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override/extend Meteor methods?

Tags:

meteor

Is it possible to somehow override a method in Meteor? Or define another function such that both will get called?

In my regular code:

Meteor.methods(
   foo: (parameters) ->
      bar(parameters)
)

Somewhere else that gets loaded later (e.g. in tests):

Meteor.methods(
   # override
   foo: (parameters) ->
      differentBehavior(parameters)
      # I could call some super() here
)

So I would expect to either have both bar and differentBehavior executed or only differentBehavior and some possibility to call super().

Does this exist?

like image 986
neo post modern Avatar asked May 07 '15 15:05

neo post modern


2 Answers

To override a method, on server side you can do:

Meteor.methods({
   'method_name': function () {
       //old method definition
   }
});

Meteor.default_server.method_handlers['method_name'] = function (args) {
    //put your new code here
};

The Meteor.default_server.method_handlers['method_name'] has to be included after the method definition.

To override a method (also know as a stub), on client side you can do:

Meteor.connection._methodHandlers['method_name'] = function (args) {
    //put your new code here
};

The Meteor.connection._methodHandlers['method_name'] has to be included after the method definition.

like image 53
Feki Zied Avatar answered Sep 23 '22 04:09

Feki Zied


There are lots of ways you can do what you are intending to do.

For instance, the simplest way to overwrite any function would be to do something like:

Meteor.publish = function() { /* My custom function code */ };

We just over-wrote the Meteor.publish with our own instance.

However, if you want to wrapper a function like a proxy (I believe this is called a "proxy pattern":

var oldPublish = Meteor.publish();
Meteor.publish = function() {
  oldPublish(arguments);   // Call old JS with arguments passed in
}

ES6 also added a Proxy object that allows you to do some similar things (read about it here).

Also there are lots of AOP libraries (CujoJS, jQuery-AOP, and node-aop to name a few) for JavaScript that allow you to do before, after, around pointcuts on functions/objects. You could even roll-your-own if you wanted too.

like image 25
CodeChimp Avatar answered Sep 22 '22 04:09

CodeChimp