Meteor in Front, Phoenix in Back - Part 1

Written by Pete Corey on Aug 15, 2016.

If you follow me on Twitter, it’s probably not surprise that I’ve been interested in Elixir and the Phoenix Framework for quite a while now. Coming from a Node.js and Meteor background, the promises of out-of-the-box reliability and scalability are incredibly attractive.

To get my feet wet, I decided to use Phoenix to build out a back-end for a simple Meteor example app.

Let’s put on our mad scientist hats and build a “Franken-stack”. We’ll be tearing the front-end out of an existing Meteor application, dropping it into a new Phoenix application, rewriting a Blaze template to use Phoenix Channels instead of DDP, and then writing a simple replacement back-end in Elixir.

Let’s get started!

Building Leaderboard

The Meteor example application we’ll be using is Leaderboard. It’s a very simple application that updates a single collection over DDP. The lack of moving parts makes it an ideal candidate for this kind of experimentation.

Let’s clone Leaderboard onto our machine and run it:


git clone https://github.com/meteor/leaderboard ~/leaderboard
cd ~/leaderboard
meteor

Fantastic! Meteor has built our Leaderboard application an moved the final build bundle into ~/leaderboard/.meteor/local/build. We’ll work more with that later.

Creating Phoenix Leaderboard

Now we need to create our new Phoenix project. Unsurprisingly, we’ll be calling this new app “Phoenix Leaderboard”. Let’s use Mix to create our application:


cd ~
mix phoenix.new phoenix_leaderboard
cd ~/phoenix_leaderboard
mix ecto.create

I’ll assume that you have a very basic understanding of a Phoenix project’s structure. If you don’t, check out the official guides for a quick introduction.

Now that we have our Phoenix project, we can start up our Phoenix server:


mix phoenix.server

Navigating to http://localhost:4000 should bring you to a “Welcome to Phoenix!” page.

Front-end Transplant

Now that we’ve laid our groundwork, we can move onto the more interesting bits of this experiment. Let’s get to work transplanting our Meteor front-end into our newly created Phoenix application.

Within our ~/leaderboard/.meteor/local/build/programs folder, our Meteor application’s font-end and back-end components are separated into the web.browser and server folders respectively.

Transplanting the front-end is really just a matter of copying over all of the required files within web.browser into our Phoenix application.

From web.browser, we’ll need the merged-stylesheets.css file, the entire app folder, and the entire packages folder. Let’s copy all of these into ~/phoenix_leaderboard/priv/static:


cp merged-stylesheets.css ~/phoenix_leaderboard/priv/static/
cp -r app ~/phoenix_leaderboard/priv/static/
cp -r packages ~/phoenix_leaderboard/priv/static/

Now we need to tell our Phoenix server that these files can be served as static assets. Let’s open up our lib/phoenix_leaderboard/endpoint.ex file and add them to our Plug.Static plug:


  plug Plug.Static,
    at: "/", from: :phoenix_leaderboard, gzip: false,
    only: ~w(app packages merged-stylesheets.css css js)

The last step of this transplant is to copy over the final HTML generated by our Meteor application. Head over to view-source:http://localhost:4000/ and copy the contents of this page into web/templates/layout/app.html.eex, replacing whatever’s already there.

That’s it!

After restarting our Phoenix server and navigating to http://localhost:4000/, we should see the (playerless) Leaderboard application!

Leveraging Brunch

Now that we’ve successfully transplanted out Meteor front-end into our Phoenix application, our next step is to wire it up to our server and start passing data.

To do this, we’re going to make some minor changes to the leaderboard Blaze template.

We’re going to be writing ES6 in this project, so we’ll want this transpiled into standard ES5-style Javascript. We can use Brunch, Phoenix’s default asset pipeline, to do this for us.

To leverage Brunch, I’m going to move the contents of priv/static/app/leaderboard.js into web/static/js/app.js, overwriting the current contents of app.js. Brunch watches web/static/js/* for changes and runs them through Babel, UglifyJS, etc… before moving it to priv/static/js/app.js.

Next, I’ll remove the self-executing function wrapper around the Blaze Template code, and import Phoenix’s socket module. Our new app.js should look something like this:


import socket from "./socket";

const Players = new Mongo.Collection("players");

Template.leaderboard.helpers({
  ...

Now we’ll change our app.html.eex file to pull in /js/app.js instead of /app/template.js:


<script src='<%= static_path(@conn, "/js/app.js") %>'></script>

Now that we’ve made these changes, we should still be able to load our new Leaderboard application without any problems.

Connecting to Channels

Now that we can freely change our leaderboard template, let’s remove our dependence on DDP and fetch player data from a Phoenix Channel instead.

Our plan of attack is to subscribe to a Channel when the leaderboard template is created and upsert any published players into our client-side Players Minimongo collection. By leveraging Minimongo, we won’t have to make any changes to our existing Meteor-style template functionality.

Let’s add an onCreated handler to our leaderboard Blaze template:


Template.leaderboard.onCreated(function() {
  this.channel = socket.channel("players");
  this.channel.join()
    .receive("ok", players => {
      players.map(player => Players.upsert(player.id, player));
    })
    .receive("error", e => console.log("Unable to join", e));
});

We’re opening a connection to a "players" Channel, and on successfully joining, we’re upserting all of the players we receive from the server into our local Players collection.

To make this work, we need to add a "players" Channel on our server.


By default, Phoenix creates a socket handler for us called PhoenixLeaderboard.UserSocket (web/channels/user_socket.ex). Here, we can define our "players" channel and assign it a controller module, PhoenixLeaderboard.PlayersChannel:


channel "players", PhoenixLeaderboard.PlayersChannel

Now let’s add a simple join handler to our new PhoenixLeaderboard.PlayersChannel (web/channels/players_channel.ex):


defmodule PhoenixLeaderboard.PlayersChannel do
  use Phoenix.Channel

  def join("players", _message, socket) do
    {:ok, [
      %{ id: 1, name: "Ada Lovelace", score: 5 },
      %{ id: 2, name: "Grace Hopper", score: 10 },
      %{ id: 3, name: "Marie Curie", score: 15 },
      %{ id: 4, name: "Carl Friedrich Gauss", score: 20 },
      %{ id: 5, name: "Nikola Tesla", score: 25 },
      %{ id: 6, name: "Claude Shannon", score: 30 }
    ], socket}
  end
end

Every time a client joins the "players" channel, we’ll send them a list of players in our reply.

If we go back to our application, we’ll see that all of our players are correctly pulled from the server and rendered in order of their score!

What’s Next and Final Thoughts

In good conscience, we should reiterate that this is just an experiment. We don’t recommend tearing a Meteor application in half and dropping its front-end into another application.

That being said, the fact that this is possible is really interesting!

It’s amazing that after dropping the Meteor front-end into our Phoenix application, we can still use all of the features of Blaze templates, Minimongo, and Session variables right out of the box!

In our next post, we’ll finish up our Franken-stack by wiring our Phoenix server up to a real database and using Channel events to implement the “Add Points” functionality.

Stay tuned!

The Captain's Distance Request

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 10, 2016.

Project Setup

Under the captain’s orders, we’ll be implementing a method that calculates the distance between two points on Earth given in degree/minute/second format.

As always, we’ll get started by creating a new project that uses Babel for ES6 transpilation and Mocha for all of our testing needs.

.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"); + +});

The Simplest Test

To get started, we’ll write the simplest test we can think of. We would expect the distance between two identical coordinates to be zero kilometers:


expect(distance(
    "48° 12′ 30″ N, 16° 22′ 23″ E",
    "48° 12′ 30″ N, 16° 22′ 23″ E"
)).to.equal(0);

At first, our test suite does not run. distance is undefined. We can easily fix that by exporting distance from our main module and importing it into our test module.

Now the suite runs, but does not pass. It’s expecting undefined to equal 0. We can fix this by having our new distance function return 0.

index.js

+export function distance(coord1, coord2) { + return 0; +}

test/index.js

import { expect } from "chai"; +import { distance } from "../"; -describe("index", function() { +describe("The captain's distance", function() { - it("works"); + it("calculates the distance between two points", () => { + let coord1 = "48° 12′ 30″ N, 16° 22′ 23″ E"; + let coord2 = "48° 12′ 30″ N, 16° 22′ 23″ E"; + + expect(distance(coord1, coord2)).to.equal(0); + });

Splitting on Lat/Lon

We can think of our solution as a series of transformations. The first transformation we need to do is splitting our comma separated lat/lon string into two separate strings. One that holds the latitude of our coordinate, and the other that holds the longitude.


expect(splitOnLatLon("48° 12′ 30″ N, 16° 22′ 23″ E")).to.deep.equal([
    "48° 12′ 30″ N",
    "16° 22′ 23″ E"
]);

We can test that a function called splitOnLatLon does just this.

Implementing splitOnLatLon is just a matter of stringing together a few Lodash function calls.

index.js

+import _ from "lodash"; + +export function splitOnLatLon(coord) { + return _.chain(coord) + .split(",") + .map(_.trim) + .value(); +} + export function distance(coord1, coord2) {

test/index.js

import { expect } from "chai"; -import { distance } from "../"; +import { + distance, + splitOnLatLon +} from "../"; ... it("calculates the distance between two points", () => { - let coord1 = "48° 12′ 30″ N, 16° 22′ 23″ E"; - let coord2 = "48° 12′ 30″ N, 16° 22′ 23″ E"; + expect(distance( + "48° 12′ 30″ N, 16° 22′ 23″ E", + "48° 12′ 30″ N, 16° 22′ 23″ E" + )).to.equal(0); + }); - expect(distance(coord1, coord2)).to.equal(0); + it("splits on lat/lon", () => { + expect(splitOnLatLon("48° 12′ 30″ N, 16° 22′ 23″ E")).to.deep.equal([ + "48° 12′ 30″ N", + "16° 22′ 23″ E" + ]); });

DMS To Decimal

The next step in our transformation is converting our coordinates from their given degree, minute, second format into a decimal format that we can use to calculate distance.

We would expect our new toDecimal function to take in a DMS string and return a decimal interpretation of that lat/lon value.


expect(toDecimal("48° 12′ 30″ N")).to.be.closeTo(48.2083, 0.001);

We can represent each DMS string as a regular expression and use ES6 destructuring to easily extract the values we care about:


let regex = /(\d+)° (\d+)′ (\d+)″ ((N)|(S)|(E)|(W))/;
let [_, degrees, minutes, seconds, __, N, S, E, W] = regex.exec(dms);

From there, we do some basic conversions and math to transform the DMS values into their decimal equivilants.

index.js

... +export function toDecimal(dms) { + let regex = /(\d+)° (\d+)′ (\d+)″ ((N)|(S)|(E)|(W))/; + let [_, degrees, minutes, seconds, __, N, S, E, W] = regex.exec(dms); + let decimal = parseInt(degrees) + + (parseInt(minutes) / 60) + + (parseInt(seconds) / (60 * 60)); + return decimal * (N || E ? 1 : -1); +} + export function distance(coord1, coord2) {

test/index.js

... distance, - splitOnLatLon + splitOnLatLon, + toDecimal } from "../"; ... + it("converts dms to decimal format", () => { + expect(toDecimal("48° 12′ 30″ N")).to.be.closeTo(48.2083, 0.001); + expect(toDecimal("48° 12′ 30″ S")).to.be.closeTo(-48.2083, 0.001); + expect(toDecimal("16° 22′ 23″ E")).to.be.closeTo(16.3730, 0.001); + expect(toDecimal("16° 22′ 23″ W")).to.be.closeTo(-16.3730, 0.001); + }); + });

The Haversine Formula

The next step in our transformation is using the two sets of latidudes and longitudes we’ve constructured to calculate the distance between our two points.

We would expect the same two points to have zero distance between them:


expect(haversine(
    48.2083, 16.3730,
    48.2083, 16.3730,
    6371
)).to.be.closeTo(0, 0.001);

And we would expect another set of points to have a resonable amount of distance between them:


expect(haversine(
    48.2083, 16.3730,
    16.3730, 48.2083,
    6371
)).to.be.closeTo(3133.445, 0.001);

The haversize function is a fairly uninteresting implementation of the Haversine Formula. After implementing this formula, our tests pass!

index.js

... +export function haversine(lat1, lon1, lat2, lon2, R) { + let dlon = lon2 - lon1; + let dlat = lat2 - lat1; + let a = Math.pow(Math.sin(dlat/2), 2) + + Math.cos(lat1) * + Math.cos(lat2) * + Math.pow(Math.sin(dlon/2), 2); + let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + return R * c; +} + export function distance(coord1, coord2) {

test/index.js

... splitOnLatLon, - toDecimal + toDecimal, + haversine } from "../"; ... it("converts dms to decimal format", () => { - expect(toDecimal("48° 12′ 30″ N")).to.be.closeTo(48.2083, 0.001); - expect(toDecimal("48° 12′ 30″ S")).to.be.closeTo(-48.2083, 0.001); - expect(toDecimal("16° 22′ 23″ E")).to.be.closeTo(16.3730, 0.001); - expect(toDecimal("16° 22′ 23″ W")).to.be.closeTo(-16.3730, 0.001); + expect(toDecimal("48° 12′ 30″ N")).to.be.closeTo(48.208, 0.001); + expect(toDecimal("48° 12′ 30″ S")).to.be.closeTo(-48.208, 0.001); + expect(toDecimal("16° 22′ 23″ E")).to.be.closeTo(16.373, 0.001); + expect(toDecimal("16° 22′ 23″ W")).to.be.closeTo(-16.373, 0.001); + }); + + it("calculates distance using the haversine formula", () => { + expect(haversine( + 48.2083, 16.3730, + 48.2083, 16.3730, + 6371 + )).to.be.closeTo(0, 0.001); + + expect(haversine( + 48.2083, 16.3730, + 16.3730, 48.2083, + 6371 + )).to.be.closeTo(3133.445, 0.001); });

Finishing the Transformation

Now that we have all of the finished pieces of our transformation we can refactor our distance function.

The basic idea is that we want to split out the lat/lon of each coordinate, convert the DMS coordinates into decimal format, pass the resulting coordinates into haversine and finally round the result.

After doing this refactoring, our tests still pass!

index.js

... export function distance(coord1, coord2) { - return 0; + return _.chain([coord1, coord2]) + .map(splitOnLatLon) + .flatten() + .map(toDecimal) + .thru(([lat1, lon1, lat2, lon2]) => haversine(lat1, lon1, lat2, lon2, 6371)) + .divide(10) + .floor() + .multiply(10) + .value(); }

Final Tests and Bug Fixes

After adding in the remaining given tests in the code kata, I noticed I was getting incorrect results form my distance function. After looking at my code, I noticed an obvious error.

My toDecimal function was returning coordinates in degrees, but the haversine function was expecting the coordinates to be in radians.

The fix to our toDecimal function was simply to convert the result to radians by multipling by Math.PI / 180:


return decimal * (N || E ? 1 : -1) * (Math.PI / 180);

After making this change and refactoring our toDecimal tests, all of our tests passed.

index.js

... (parseInt(seconds) / (60 * 60)); - return decimal * (N || E ? 1 : -1); + return decimal * (N || E ? 1 : -1) * (Math.PI / 180); }

test/index.js

... )).to.equal(0); + + expect(distance( + "48° 12′ 30″ N, 16° 22′ 23″ E", + "23° 33′ 0″ S, 46° 38′ 0″ W" + )).to.equal(10130); + + expect(distance( + "48° 12′ 30″ N, 16° 22′ 23″ E", + "58° 18′ 0″ N, 134° 25′ 0″ W" + )).to.equal(7870); }); ... it("converts dms to decimal format", () => { - expect(toDecimal("48° 12′ 30″ N")).to.be.closeTo(48.208, 0.001); - expect(toDecimal("48° 12′ 30″ S")).to.be.closeTo(-48.208, 0.001); - expect(toDecimal("16° 22′ 23″ E")).to.be.closeTo(16.373, 0.001); - expect(toDecimal("16° 22′ 23″ W")).to.be.closeTo(-16.373, 0.001); + expect(toDecimal("48° 12′ 30″ N")).to.be.closeTo(0.841, 0.001); + expect(toDecimal("48° 12′ 30″ S")).to.be.closeTo(-0.841, 0.001); + expect(toDecimal("16° 22′ 23″ E")).to.be.closeTo(0.285, 0.001); + expect(toDecimal("16° 22′ 23″ W")).to.be.closeTo(-0.285, 0.001); });

Final Thoughts

Lately, we’ve been playing around with functional programming and languages like Elixir. Functional languages encourage you to express your programs as a series of pure transformations of your data.

This practice problem definitely shows some influences from that style of thinking. We leaned heavily on Lodash and wrote most of our functions as neatly chained transformations of their arguments.

While Javascript may not be the best language for writing code in this style, I’m a big fan of these kind of functional transformation pipelines. I feel like they produce very clear, very easily to follow functions and programs.

Be sure to check out the Github repo if you want to see the final source for this project!

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.