Where should Meteor.methods() be defined?

后端 未结 4 700
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 15:31

http://docs.meteor.com/#meteor_methods

I have tried it in publish.js in my server folder.

I am successfully calling Meteor.apply and attempting the server ca

相关标签:
4条回答
  • 2020-12-13 15:58

    There are several places I can define my Meteor.methods() (with pro's and con's):

    1. On the server only - when the client calls the method, it'll have to wait for the server to respond before anything changes on the client-side
    2. On the server, and uses a stub on the client - when the client calls the method, it will execute the stub method on the client-side, which can quickly return a (predicted) response. When the server comes back with the 'actual' response, it will replace the response generated by the stub and update other elements according.
    3. The same method on both client and server - commonly used for methods dealing with collections, where the method is actually a stub on the client-side, but this stub is the same as the server-side function, and uses the client's cached collections instead of the server's. So it will still appear to update instantly, like the stub, but I guess it's a bit more accurate in its guessing.
    0 讨论(0)
  • 2020-12-13 15:59

    Calling Meteor.methods on the server is correct. That will define remote methods that run in the privileged environment and return results to the client. To return a normal result, just call return from your method function with some JSON value. To signal an error, throw a Meteor.Error.

    On the client, Meteor.apply always returns undefined, because the method call is asynchronous. If you want the return value of the method, the last argument to apply should be a callback, which will be passed two arguments: error and result, in the typical async callback style.

    Is your server code actually getting called? You can check that by updating the DB in the method and seeing if the client's cache gets the new data, or calling console.log from inside the method body and looking at the output of the "meteor" process in your terminal.

    0 讨论(0)
  • 2020-12-13 16:07

    I've uploaded a short example here, should you need a working example of this: https://gist.github.com/2387816

    0 讨论(0)
  • 2020-12-13 16:14

    I hope some will find use of this addition, and this doesn't cloud the issue that methods are primarily intended to run on the server as debergalis has explained.

    Using Meteor.methods() on the client is useful too. (look for "stub" in the Meteor.call() section too...) This allows the client to (synchronously) simulate the expected effect of the server call. As mentioned in the docs:

    You use methods all the time, because the database mutators (insert, update, remove) are implemented as methods. (...)

    A separate section explaining use of stubs on the client might ease the understanding of methods calls on the server.

    0 讨论(0)
提交回复
热议问题