Duplication of method code between client and server

If I have a method that needs to run some different code on the server and the client, I can use a Meteor.isServer block to identify the server only parts, this is nice because I dont have to repeat the boiler plate code:

export const updateText = new ValidatedMethod({
  name: 'todos.updateText',
  validate: new SimpleSchema({
    todoId: { type: String },
    newText: { type: String }
  }).validator(),
  run({ todoId, newText }) {
    if(Meteor.isServer) {
     // some super cool stuff
    }
  }
});

But if my server side code depends on packages that are not available on the client, how can I make sure those import process only on the server side? I want to do something like this - leaving my boiler plate and simulation code in a shared file, then have a second file with the server specific code, from which I could do all my imports:

export const updateText = new ValidatedMethod({
  name: 'todos.updateText',
  validate: new SimpleSchema({
    todoId: { type: String },
    newText: { type: String }
  }).validator(),
  run({ todoId, newText }) {
    if(Meteor.isServer) {
      import {updateText} from './server/methods';
      updateText();
    }
  }
});

It seems to work, but is that the way the import is supposed to work? What is the best practice?

Your nested import will work if you’re using Meteor 1.3.3 or higher. Meteor switched to using @benjamn’s Reify transpiler, which exists only to support nested imports.

Currently, this goes against ES6 specs, but Ben’s got some solid arguments about why it might be a good idea to allow this and change the specifications. He’s going to be presenting to the EcmaScript committee about it at the end of the month.

If you want to stay as ES6-compliant as you can, your other options would be to define the server-side version of your method in a server-only location (/server) and use a top level import, or forgo ES6 modules entirely and use a nested require statement.

I’ve actually got a article about all of this coming down the pipe. It’ll be out on Monday if you’re interested in more details.

2 Likes

Thank you, I will be looking for the article! I read the notes from @benjamn and it makes sense to me especially in the context of Meteor apps, so I will be using that in the meantime.