Module Import Organization

Written by Pete Corey on Aug 8, 2016.

In our last post discussing the benefits of moving your methods, publications, and templates into modules, we mentioned that all of this Meteor-specific functionality relied on modifying global state.

This means that our modules didn’t need to export anything. However, they do need to be imported at least once by your main Meteor application.

Importing these modules executes your calls to Meteor.methods(...), Meteor.publish(...), etc… and makes them accessible to the rest of your application.

Depending on how you structure your imports, this kind of upfront importing can quickly get out of hand.

The Problem With Direct Imports

Imagine we have an /imports/lib folder in our project. Within that folder we break up our application’s functionality into distinct components, like foo and bar. Each component has it’s own set of Meteor methods defined in a methods.js file:


.
└── imports
    └── lib
        ├── bar
        │   └── methods.js
        └── foo
            └── methods.js

To make sure these methods are registered when our application starts, we’ll need to update both our /client/mains.js and our /server/main.js to import these method files:


import "/imports/lib/foo/methods";
import "/imports/lib/bar/methods";

This import structure seems to make sense so far.

It might get more difficult to deal with if we start to aggressively break up our methods, but we’ll put that out of our minds for now.


When we begin adding template modules, our /imports folder structure will quickly begin to balloon in size:


.
└── imports
    ├── client
    │   ├── bar
    │   │   ├── template-1
    │   │   │   ├── template-1.js
    │   │   │   └── template-2.html
    │   │   └── template-2
    │   │       └── ...
    │   └── foo
    │       ├── template-3
    │       │   ├── template-3.js
    │       │   └── template-3.html
    │       └── template-4
    │           └── ...
    └── lib
        ├── bar
        │   └── methods.js
        └── foo
            └── methods.js

Now we’ll have to update our /client/main.js to pull in each of these templates:


import "/imports/lib/foo/methods";
import "/imports/lib/bar/methods";

import "/imports/client/bar/template-1/template-1";
import "/imports/client/bar/template-2/template-2";
import "/imports/client/foo/template-3/template-3";
import "/imports/client/foo/template-4/template-4";

Our /client/main.js file has to keep up with every defined method and template in the system. Similarly, our /server/main.js will have to keep up with ever method definition and publication definition (and potentially every template definition, if we’re using SSR).

This breaks the clean modularity of our system. Our main.js files need to be intimately aware of the structure and implementation of all of our component pieces.

Index Files to the Rescue

Thankfully, index files can lead us out of this increasingly hairy situation.

When an index.js file is present in a directory, attempting to import that directory will cause the index.js file to be imported on its behalf. For example, consider this folder structure:


.
└── baz
    └── index.js

If we import "baz" (import "./baz"), index.js will be imported instead.

We can leverage this to organize our /imports structure and clean up our main.js files. Let’s start by adding an index.js file to each method and template “component”:


.
└── imports
    ├── client
    │   ├── bar
    │   │   ├── template-1
    │   │   │   ├── index.js
    │   │   │   ├── template-1.js
    │   │   │   └── template-2.html
    │   │   └── template-2
    │   │       └── ...
    │   └── foo
    │       └── ...
    └── lib
        ├── bar
        │   │── index.js
        │   └── methods.js
        └── foo
            └── ...

Our /imports/client/bar/template-1/index.js file only needs to be concerned about importing the files related to the template-1 component:


import "./template-1";

Similarly, our /imports/lib/bar/index.js file only needs to be concerned about importing the method and other server-side functionality related to the bar component:


import "./methods.js";

Fantastic. Now, let’s move up in our folder tree, adding index.js files at each step along the way until we hit our client, lib, or server folders:


.
└── imports
    ├── client
    │   ├── index.js
    │   ├── bar
    │   │   ├── index.js
    │   │   ├── template-1
    │   │   │   ├── index.js
    │   │   │   ├── template-1.js
    │   │   │   └── template-2.html
    │   │   └── template-2
    │   │       └── ...
    │   └── foo
    │       └── ...
    └── lib
        ├── index.js
        ├── bar
        │   │── index.js
        │   └── methods.js
        └── foo
            └── ...

Our newly created /imports/client/bar/index.js file is concerned about importing all of the templates and functionality related to the bar component:


import "./template-1";
import "./template-2";

We can finish up our import chain on the client by updating our new /imports/client/index.js file to import the foo and bar client-side components:


import "./bar";
import "./foo";

We can do the same thing in our /imports/lib folder by updating our new /imports/server/index.js file:


import "./bar";
import "./foo";

Finally, we can drastically simplify our /client/main.js and /server/main.js files to only pull in what we need at a very high level.

On the client (/client/main.js), we’ll just want to import client-only and shared components:


import "/imports/lib";
import "/imports/client";

And on the server (/server/main.js), we (currently) only want to import the shared components:


import "/imports/lib";

If we had a set of server-only components we could easily include it there as well.

Reaping the Benefits

I’m a big fan of this structure.

Each level of our dependency tree only has to concern itself with the next level. Our client folder only has to know that it wants to pull in the foo and bar components. It doesn’t need to know which templates those components use. The foo and bar components manage the importing of their templates themselves!

If you wanted to add a new template to the bar component, you’d simply add the template folder into /imports/client/bar/, with an index file that pulls in the required files. Lastly, you’d update /imports/client/bar/index.js to import that new template.

Removing a template is as simple as deleting its folder and removing the import reference from its parent’s index.js file.

Nesting Structure Comparison

This post is written as a set of Literate Commits. The goal of this style is to show you how this program came together from beginning to end.

Each commit in the project is represented by a section of the article. Click each section's header to see the commit on Github, or check out the repository and follow along.

Written by Pete Corey on Aug 3, 2016.

Project Setup

The goal of this code kata is to implement a method on the Array prototype that determines when the current array and another array provided as input have the same nested structure.

To get a better idea of what we mean by “nested structure”, these calls to sameStructureAs would return true:


[ 1, 1, 1 ].sameStructureAs( [ 2, 2, 2 ] );
[ 1, [ 1, 1 ] ].sameStructureAs( [ 2, [ 2, 2 ] ] );

And these would return false:


[ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2, 2 ], 2 ] );
[ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2 ], 2 ] );

We’ll start by initializing our project with a basic Babel and Mocha setup.

.babelrc

+{ + "presets": ["es2015"] +}

.gitignore

+node_modules/

package.json

+{ + "main": "index.js", + "scripts": { + "test": "mocha ./test --compilers js:babel-register" + }, + "dependencies": { + "babel-preset-es2015": "^6.9.0", + "babel-register": "^6.9.0", + "chai": "^3.5.0", + "lodash": "^4.12.0", + "mocha": "^2.4.5" + } +}

test/index.js

+import { expect } from "chai"; + +describe("index", function() { + + it("works"); + +});

Extending Array

The simplest test we can write to get going is to compare the structure of an empty array to another empty array:


expect([].sameStructureAs([])).to.be.true;

After writing this test, our test suite fails. A naively simple way to get our suite back into the green is to define a very simple sameStructureAs function on the Array prototype that always returns true.

index.js

+Array.prototype.sameStructureAs = function(other) { + return true; +}

test/index.js

+import "../"; import { expect } from "chai"; -describe("index", function() { +describe("sameStructureAs", function() { - it("works"); + it("works", () => { + expect([].sameStructureAs([])).to.be.true; + });

Comparing Types

Next, we’ll add our first real test. We expect an array who’s first element is a Number to have a different structure than an array who’s first element is an Array:


expect([1].sameStructureAs([[]])).to.be.false;

The most obvious way to make this test pass is to check the types of the first element of each array. If both first elements are arrays, or both are not arrays, we’ll return true. Otherwise, we’ll return false.

index.js

+import _ from "lodash"; + Array.prototype.sameStructureAs = function(other) { - return true; + if (_.isArray(this[0]) && _.isArray(other[0])) { + return true; + } + else if (!_.isArray(this[0]) && !_.isArray(other[0])) { + return true; + } + return false; }

test/index.js

... expect([].sameStructureAs([])).to.be.true; + expect([1].sameStructureAs([[]])).to.be.false; });

Generalizing

Now that we have our base case figured out, it’s time to generalize and check the structure of arrays of any length.

To guide us on this process, we added two new tests:


expect([[], []].sameStructureAs([[], []])).to.be.true;
expect([[], 1].sameStructureAs([[], []])).to.be.false;

The general idea is that we’ll want to compare each element of this and other using the same kind of structural comparison we previously wrote. Lodash’s _.zipWith function is a great way of comparing array elements like this:


let comparisons = _.zipWith(this, other, (a, b) => {
    ...
});

Now, comparisons will hold a list of true/false values representing whether the values at that position shared the same structure.

We can use _.every to return true if all comparisons are true, or false otherwise.

During this process, we also did some refactoring of our comparison code, just to clean things up a bit:


let bothArrays = _.isArray(a) && _.isArray(b);
let bothNot = !_.isArray(a) && !_.isArray(b);
return bothArrays || bothNot;

index.js

... Array.prototype.sameStructureAs = function(other) { - if (_.isArray(this[0]) && _.isArray(other[0])) { - return true; - } - else if (!_.isArray(this[0]) && !_.isArray(other[0])) { - return true; - } - return false; + let comparisons = _.zipWith(this, other, (a, b) => { + let bothArrays = _.isArray(a) && _.isArray(b); + let bothNot = !_.isArray(a) && !_.isArray(b); + return bothArrays || bothNot; + }); + return _.every(comparisons); }

test/index.js

... expect([1].sameStructureAs([[]])).to.be.false; + expect([[], []].sameStructureAs([[], []])).to.be.true; + expect([[], 1].sameStructureAs([[], []])).to.be.false; });

Getting Recursive

So far we’ve only handled a single layer of structure. However, the goal of sameStructureAs is to compare the nested structures of our inputs. Consider these examples:


expect([[], [1]].sameStructureAs([[], [1]])).to.be.true;
expect([[], [1]].sameStructureAs([[], [[]]])).to.be.false;

While at first glance this seems to add a lot of complexity, there’s actually a very elegant solution to this problem. When we find two matching arrays in our inputs, all we need to do is ensure that the contents of those arrays have the same structure:


return (bothArrays && a.sameStructureAs(b)) || bothNot;

This recursive call into sameStructureAs will handle any nested depths that we can throw at it (as long as we don’t blow our stack).

index.js

... let bothNot = !_.isArray(a) && !_.isArray(b); - return bothArrays || bothNot; + return (bothArrays && a.sameStructureAs(b)) || bothNot; });

test/index.js

... expect([[], 1].sameStructureAs([[], []])).to.be.false; + expect([[], [1]].sameStructureAs([[], [1]])).to.be.true; + expect([[], [1]].sameStructureAs([[], [[]]])).to.be.false; });

Bug Fixes

Submitting our solution revealed a few bugs in our solution. The first bug can be pointed out with this failing test:


expect([].sameStructureAs(1)).to.be.false;

We were assuming that other would be an array. Unfortunately in this case, other is 1, which causes _.zipWith to return an empty array.

We can fix this bug by adding an upfront check asserting that other is an Array.

After fixing that issue, another bug reared its ugly head:


expect([1].sameStructureAs([1, 2])).to.be.false;

In the last iteration of _.zipWith, a was undefined and b was 2. While checking if both of these values were not arrays returned true, we didn’t check if both values actually existed.

The fix for this bug is to check that both a and b are not undefined:


let bothDefined = !_.isUndefined(a) && !_.isUndefined(b);
let bothNot = bothDefined && !_.isArray(a) && !_.isArray(b);

With those fixes, out suite flips back to green!

index.js

... Array.prototype.sameStructureAs = function(other) { + if (!_.isArray(other)) { + return false; + } let comparisons = _.zipWith(this, other, (a, b) => { let bothArrays = _.isArray(a) && _.isArray(b); - let bothNot = !_.isArray(a) && !_.isArray(b); + let bothDefined = !_.isUndefined(a) && !_.isUndefined(b); + let bothNot = bothDefined && !_.isArray(a) && !_.isArray(b); return (bothArrays && a.sameStructureAs(b)) || bothNot;

test/index.js

... expect([[], [1]].sameStructureAs([[], [[]]])).to.be.false; + expect([].sameStructureAs(1)).to.be.false; + expect([1].sameStructureAs([1, 2])).to.be.false; });

Final Refactor

To make things a little more readable, I decided to move the undefined check into a guard, rather than including it withing the comparison logic of our zipWith function.

After implementing this refactor, our tests still pass.

index.js

... let comparisons = _.zipWith(this, other, (a, b) => { + if (_.isUndefined(a) || _.isUndefined(b)) { + return false; + } let bothArrays = _.isArray(a) && _.isArray(b); - let bothDefined = !_.isUndefined(a) && !_.isUndefined(b); - let bothNot = bothDefined && !_.isArray(a) && !_.isArray(b); + let bothNot = !_.isArray(a) && !_.isArray(b); return (bothArrays && a.sameStructureAs(b)) || bothNot;

Final Thoughts

Looking at the other submitted solutions to this kata, I realize that it’s a fairly interesting problem with lots of possible solutions. There are shorter solutions out there, but I like ours for its readability.

Brevity doesn’t always lead to better code. This is an important lesson that has taken me many years to fully appreciate.

Be sure to check out the final solution on GitHub. If you spot a bug or see a place ripe for improvement, be sure to submit a pull request!

Method Imports and Exports

Written by Pete Corey on Aug 1, 2016.

Organizing our Meteor code into modules can be a powerful improvement over the old globals-everywhere approach that many of us are used to.

Modules emphasize isolation. Everything within a module is scoped locally within that module, unless its explicitly exported to the outside world. This kind of isolation can lead to better readability and testability.

Unfortunately, many of the core features of the Meteor framework still rely on modifying global state. Defining things like methods, publications and template helpers all update the global state of the application.

This dichotomy can be confusing to Meteor developers new to the module system. How do we define methods in modules? Should we be exporting methods from modules? How do we import those methods into our application?

Importing Methods

When you call Meteor.methods(...), you’re modifying your application’s global state. The methods you pass into Meteor.methods are pushed onto the global list of callable methods within your application.

Because it affects global state in this way, Meteor.methods is said to have side effects.

Imagine that we have a module called paymentMethods.js. The purpose of this module is to define several Meteor methods related to payment processing.

Inside of that module, we have a createPayment method that lets logged in users create new payments based on some provided options. It looks something like this:


import { Meteor } from "meteor/meteor";

Meteor.methods({
    createPayment(options) {
        if (this.userId) {
            ...
        }
        else {
            throw new Meteor.Error("unauthenticated");
        }
    }
});

You’ll notice that nothing is being exported from this module. This is because the call to Meteor.methods is modifying the global state for us. We don’t need to export our methods to make them accessible outside of the module.

We could even define our methods locally and make them accessible globally using Meteor.methods:


import { Meteor } from "meteor/meteor";

const methods = {
    createPayment(options) {
        ...
    }
};

Meteor.methods(methods);

We’ve moved our method definitions into a constant called methods which is only accessible within our paymentMethods.js module. However, our call to Meteor.methods still pulls our methods into our global method map, making them accessible anywhere in our application.


While we don’t need to export our methods from our modules, we still need some piece of our application to import our paymentMethods.js module. If our code never runs, our methods will never be defined and added to our list of global methods.

In our /server/main.js file, we can import our paymentMethods.js module. This will run our module’s code, defining the methods and passing them into Meteor.methods:


import "/imports/paymentMethods.js";

Notice that we’re not importing anything from paymentMethods.js. That’s because there is nothing to import. We just want this module to be executed.

Testing Methods

What if we wanted to unit test our paymentMethods.js module?


it("creates a payment", function() {
    let options = { type: "cc", ... };
    // TODO: call createPayment?
    expect(paymentId).to.be.ok;
});

How would we call createPayment? The obvious answer would be to use Meteor.call:


it("creates a payment", function() {
    let options = { type: "cc", ... };
    let paymentId = Meteor.call("createPayment", options);
    expect(paymentId).to.be.ok;
});

But, our method is expecting a logged in user. This leads to all kinds of difficulties.

To successfully Meteor.call our "createPayment" method, we’ll have to either override Meteor.call with a version that passes in a custom this context that we can control, or go through the process of creating and logging in as an actual user before calling "createPayment".

Following these approaches, this kind of test arguably isn’t a unit test. It relies on the entire Meteor method and accounts infrastructures to execute.

A possible way around these problems is to try to access and call our method functions directly. On the server, Meteor.call moves your method definitions into an internal object accessible through Meteor.server.method_handlers.

In theory, we could call "createPayment" directly through this object, and pass in a custom userId:


it("creates a payment", function() {
    let options = { type: "cc", ... };
    let createPayment = Meteor.server.method_handlers.createPayment;
    let paymentId = createPayment.bind({
        userId: "1234567890"
    })(options);
    expect(paymentId).to.be.ok;
});

While this works, it’s a very fragile solution. Meteor.server.method_handlers is an undocumented API and is subject to change. It’s dangerous to rely on this internal structure when there is no guarantee that it will be around in future versions of Meteor.

There has to be an better way to test our methods!

Exporting Methods

To solve this problem, let’s go back and revisit our paymentMethods.js module:


import { Meteor } from "meteor/meteor";

const methods = {
    createPayment(options) {
        ...
    }
};

Meteor.methods(methods);

We can make the testing of this module vastly easier with one simple change:


import { Meteor } from "meteor/meteor";

export const methods = {
    createPayment(options) {
        ...
    }
};

Meteor.methods(methods);

By exporting the methods object, we can now get a direct handle on our "createPayment" method without having to dig through the Meteor internals. This makes our test much more straightforward:


import { methods } from "./paymentMethods.js";

it("creates a payment", function() {
    let options = { type: "cc", ... };
    let paymentId = methods.createPayment.bind({
        userId: "1234567890"
    })(options);
    expect(paymentId).to.be.ok;
});

This is a clean test.

We’re directly calling our "createPayment" method with a controllable this context and input options. This makes it very easy to test a variety of situations and scenarios that this method might encounter.

We’re not relying on any Meteor infrastructure or internal structures to run our tests; they’re completely independent of the platform.

Beyond Methods

What’s beautiful about this module-based approach is that it’s not limited to just Meteor methods. We could apply this same technique to creating and testing our publications and our template helpers, lifecycle callbacks and event handlers.

As a quick example, imagine defining a template in a module like this:


import { Template } from "meteor/templating";

export function onCreated() {
    this.subscribe("foo");
    ...
};

export const helpers = {
    foo: () => "bar",
    ....
};

export const events = {
    "click .foo": function(e, t) {
        ...
    }
};

Template.foo.onCreated(onCreated);
Template.foo.helpers(helpers);
Template.foo.events(event);

Because we’re defining our template’s helpers, events, and onCreated callback as simple functions and objects, we can easily import them into a test module and test them directly:


import { events, helpers, onCreated} from "./foo.js";

describe("foo", function() {

    it("sets things up when it's created", function() {
        let subscriptions = [];

        onCreated.bind({
            subscribe(name) => subscriptions.push(name);
        })();
        
        expect(subscriptions).to.contain("foo");
    });

    it("returns bar from foo", function() {
        let foo = helpers.foo();
        expect(foo).to.equal("bar");
    });

    ...
});

Our onCreated test creates a custom version of this.subscribe that pushes the subscription name onto an array, and after calling the onCreated callback, asserts that "foo" has been subscribed to.

The helpers.foo test is less complex. It simply asserts that helpers.foo() equals "bar".

Final Thoughts

Hopefully I’ve given you a clear picture of how I approach defining and testing my methods, publications, and template helpers in a post-1.3 world.

Modules are a very powerful tool that can make our lives as developers much easier if we take the time to explore and understand their full potential. Modularity makes code readability, testability, and re-usability significantly easier.

Happy modularizing!