Can I override / extend Meteor methods?

Is there any way to override the method in Meteor? Or define another function so that both are called?

In my regular code:

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

In another place that loads later (e.g. in tests ):

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

Thus, I would expect both to execute both bar and differentBehavior or just differentBehavior and there is a possibility to call super() .

Does it exist?

+6
source share
2 answers

To override the method, on the server side you can:

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

Meteor.default_server.method_handlers['method_name'] should be included after the method definition.

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

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

Meteor.connection._methodHandlers['method_name'] should be included after the method definition.

+4
source

There are many ways to do what you intend to do.

For example, the easiest way to rewrite any function is to do something like:

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

We just rewrote Meteor.publish with our own copy.

However, if you want to wrap the function as a proxy (I believe this is called a "proxy template":

 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 ).

There are also many AOPs ( CujoJS , jQuery-AOP and node-aop , to name a few) for JavaScript, which allow you to do before, after, around pointcut on functions / objects. You can even ride yourself if you want.

+2
source

Source: https://habr.com/ru/post/986761/


All Articles