Meteor Tricks: import/export methods

Just a useful trick


Meteor methods are like global functions. You can not import/export them:

// methods.js
Meteor.methods({
 'messages.create': function(message) {
   // ...
 },
});


// some-other-file.js
Meteor.call('messages.create', { text: 'hello' });

But there is a solution:

// methods.js
import method from './makeMethod';

const createMessage = method('messages.create', function(message) {
 // ...
});

export { createMessage };


// some-other-file.js
import { createMessage } from 'methods';

createMessage({ title: 'hello' });

How it works:

import { Meteor } from 'meteor/meteor';

function makeMethod(name, fn) {
  Meteor.methods({ [name]: fn });

  return (...args) => {
    Meteor.call(name, ...args);
  };
}

export default makeMethod;

Great trick - you can also use the Guide’s recommended advanced Method approach of leveraging mdg:validated-method (which allows you to import/export).

1 Like

I tried to use validated-method, but it’s pretty complicated, does a lot of things, that I don’t really need)

1 Like

Yeah I love that you have a simpler way to get some of the benefits! ValidatedMethod is kind of like “enterprise methods” with all of the bells and whistles :]

1 Like