Search code examples
javascriptmeteorpublish-subscribemeteor-publications

Should Meteor publication functions be named?


I'm trying to get a better understanding of how the publication / subscription model works.

Specifically I'm referring to this step in the tutorial.

if (Meteor.isServer) {
  Meteor.publish('tasks', function tasksPublication() {
    return Tasks.find();
  });
}

The name tasksPublication isn't used anywhere later on in the tutorial.

Looking at the documentation here the name doesn't seem to be needed.
Does it make any difference to name a publication function?


Solution

  • Using named functions is indeed not needed when publishing, all these work:

    Meteor.publish('tasks', function publishAllTasks() { return Tasks.find() });
    Meteor.publish('tasks', function() { return Tasks.find() });
    Meteor.publish('tasks', () => Tasks.find());
    

    (The third line features an Arrow function)

    There is no raw difference in functionality, and choosing between the three mostly boils down to taste.

    However, there is one one thing that only the first statement (named function expression) does: the name appears in stack traces when an uncaught exception occurs.

    For example let's say you make a typo when writing Tasks and write Waffles instead:

    // File: server/index.js
    
    Meteor.publish('tasks', function publishAllTasks() { return Waffles.find() });
    // or:
    Meteor.publish('tasks', () => Waffles.find());
    

    Here is the stack trace in the first case (I removed timestamps)

    Exception from sub tasks id egG3xJuLTLFvH4jLT ReferenceError: Waffles is not defined
    at Subscription.publishAllTasks [as _handler] (server/index.js:4:10)
    (some boring stuff)

    Stack trace in the second case:

    Exception from sub tasks id u4rKBFH78uTBEoys2 ReferenceError: Waffles is not defined
    at Subscription._handler (server/index.js:4:10)
    (more boring stuff)

    In the first case the function name appears clearly.
    The file name and line still appear at the end of the line.

    So it could be helpful if you are crawling through your logs to find all uncaught exceptions that originated from / passed through publishAllTasks.
    It won't help a lot when debugging though since you still have the file name and line and finding the faulty function is just a matter of opening that file.


    So unless you have specific log-crawling needs don't bother and go for whichever you prefer.