How can I get the name of the current Meteor method?
Can I get the name of the currently executing Meteor method (internally the same)? This would be handy for logging.
I checked this
inside the Meteor method. It is an instance MethodInvocation
and has nothing useful for defining a method name.
It looks like it would be enough to just add the method name to MethodInvocation
and callers, but I'm not sure the maintainers would agree with the patch that added a field name
for each instance MethodInvocation
.
Cross reference here .
source to share
It's not ideal, but here's how you could get the monkey patch Meteor.methods
to get this functionality, for example, tubailo suggests:
var currentMethod = new Meteor.EnvironmentVariable();
function log(message) {
var method = currentMethod.get();
if (method) {
console.log(method + ": " + message);
} else {
console.log(message);
}
}
var oldMeteorMethods = Meteor.methods;
Meteor.methods = function (object) {
var methods = {};
_.each(object, function (func, name) {
methods[name] = function () {
var self = this;
var args = _.toArray(arguments);
return currentMethod.withValue(name, function() {
return func.apply(self, args);
});
};
});
oldMeteorMethods(methods);
}
Meteor.methods({
example: function (arg1, arg2) {
log("hello");
return doSomethingElse(arg1) + arg2;
}
});
function doSomethingElse(x) {
log("doSomethingElse called with " + x);
return x * 2;
}
// Meteor.call("example", 5, 6) logs:
// "example: hello"
// "example: doSomethingElse called with 5"
If you prefer non-monkey patch:
defineMethods = function (object) {
var methods = {};
_.each(object, function (func, name) {
methods[name] = function () {
var self = this;
var args = _.toArray(arguments);
return currentMethod.withValue(name, function() {
return func.apply(self, args);
});
};
});
Meteor.methods(methods);
}
defineMethods({
example: function (arg1, arg2) {
log("hello");
return doSomethingElse(arg1) + arg2;
}
});
source to share
I've reworked @ user337's answer a bit. Now you can use the function @name
inside the method.
Add this to your server code (coffeescript):
currentMethod = new Meteor.EnvironmentVariable()
oldMeteorMethods = Meteor.methods
Meteor.methods = (object) ->
methods = {}
_.each object, (func, name) ->
methods[name] = ->
args = _.toArray(arguments)
this.name = name
currentMethod.withValue name, =>
func.apply this, args
oldMeteorMethods methods
source to share