Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Meteor Design Patterns
Meteor Design Patterns

Meteor Design Patterns: Accelerate your code writing skills with over twenty programming patterns that will make your code easier to maintain and scale

eBook
$9.99 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Meteor Design Patterns

Chapter 1. Getting Started with Meteor

Meteor is a framework that is essentially fast for the purpose of development even if you program at a slow pace. The aim of this book is to increase your development speed and improve quality. There are two key ingredients required to improve development: compilers and patterns. Compilers add functionality to your coding language, while patterns increase the speed at which you solve common programming issues.

This book will mostly cover patterns, but we'll use this chapter to quick start compilers and understand how they relate to Meteor—a vast but simple topic. The compilers that we will look at are as follows:

  • CoffeeScript
  • Jade
  • Stylus

We will review some basic knowledge you should have about Meteor. This will cover the following:

  • Templates, helpers, and events
  • The event loop and the merge box
  • The must-have packages
  • Folder structure

CoffeeScript for Meteor

CoffeeScript is a compiler for JavaScript that adds "syntactic sugar" inspired by Ruby, Python, and Haskell; it effectively makes the writing of JavaScript easier and more readable. CoffeeScript simplifies the syntax of functions, objects, arrays, logical statements, binding, managing scope, and much more. All CoffeeScript files are saved with a .coffee extension. We will cover functions, objects, logical statements, and bindings as these are some of the most commonly used features.

Objects and arrays

CoffeeScript gets rid of curly braces ({}), semicolons (;), and commas (,). This alone saves you from repeating unnecessary strokes on the keyboard. Instead, CoffeeScript emphasizes on the proper use of tabbing. Tabbing will not only make your code more readable, but it will be a key factor in making the code work as well. In fact, you are probably already tabbing the right way! Let's look at some examples:

#COFFEESCRIPT
toolbox =
  hammer:true
  flashlight:false

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Here, we are creating an object named toolbox that contains two keys: hammer and flashlight. The equivalent in JavaScript will be this:

//JAVASCRIPT - OUTPUT
var toolbox = {
  hammer:true,
  flashlight:false
};

Much easier! As you can see, we have to tab to indicate that both the hammer and flashlight properties are a part of toolbox. The var word is not allowed in CoffeeScript because CoffeeScript automatically applies it for you. Let's have a look at how we would make an array:

#COFFEESCRIPT
drill_bits = [
  "1/16 in"
  "5/64 in"
  "3/32 in"
  "7/64 in"
]

//JAVASCRIPT – OUTPUT
var drill_bits;
drill_bits = ["1/16 in","5/64 in","3/32 in","7/64 in"];

Here, we can see that we don't need to have any commas, but we do need to have brackets to determine that this is an array.

Logical statements and operators

CoffeeScript removes a lot of parenthesis (()) in logical statements and functions as well. This makes the logic of the code much easier to understand at first glance. Let's look at an example:

#COFFEESCRIPT
rating = "excellent" if five_star_rating

//JAVASCRIPT – OUTPUT
var rating;

if(five_star_rating){
  rating = "excellent";
}

In this example, we can clearly see that CoffeeScript is easier to read and write. CoffeeScript effectively replaces the entire implied parenthesis in any logical statement.

Operators such as &&, ||, and !== are replaced by words to make the code more readable. Here is a list of the operators that you will be using the most:

CoffeeScript

JavaScript

is

===

isnt

!==

not

!

and

&&

or

||

true, yes, on

true

false, no, off

false

@, this

this

Let's look at a slightly more complex logical statement and see how it is compiled:

#COFFEESCRIPT
# Suppose that "this" is an object that represents a person and their physical properties

if @eye_color is "green"
  retina_scan = "passed"
else
  retina_scan = "failed"

//JAVASCRIPT - OUTPUT
if(this.eye_color === "green"){
  retina_scan = "passed";
} else {
  retina_scan = "failed";
}

Notice how the context of this is passed to the @ symbol without the need for a period, making @eye_color equal to this.eye_color.

Functions

A JavaScript function is a block of code designed to perform a particular task. JavaScript has a couple of ways of creating functions that are simplified in CoffeeScript. They look like this:

//JAVASCRIPT
//Save an anonymous function onto a variable
var hello_world = function(){
  console.log("Hello World!");
}

//Declare a function
function hello_world(){
  console.log("Hello World!");
}

CoffeeScript uses -> instead of the function() keyword. The following example outputs a hello_world function:

#COFFEESCRIPT
#Create a function
hello_world = ->
  console.log "Hello World!"

//JAVASCRIPT - OUTPUT
var hello_world;
hello_world = function(){
  return console.log("Hello World!");
}

Once again, we will use a tab to specify the contents of the function so that there is no need for curly braces ({}). This means that you have to make sure that you have the entire logic of the function tabbed under its namespace.

What about our parameters? We can use (p1,p2) -> where p1 and p2 are parameters. Let's make our hello_world function output our name:

#COFFEESCRIPT
hello_world = (name) ->
  console.log "Hello #{name}"

//JAVSCRIPT – OUTPUT
var hello_world;
hello_world = function(name) {
  return console.log("Hello " + name);
}

In this example, we can see how parameters are placed inside parentheses. We are also doing string interpolation. CoffeeScript allows the programmer to easily add logic to a string by escaping the string with #{}. Also notice that, unlike JavaScript, you do not have to return anything at the end of the function, CoffeeScript automatically returns the output of the last command.

Binding

In Meteor, we will often find ourselves using the properties of this within nested functions and callbacks. Function binding is very useful for these types of cases and helps to avoid saving data in additional variables. Function binding sets the value of the this object inside the function to the value of this outside the function. Let's look at an example:

#COFFEESCRIPT
# Let's make the context of this equal to our toolbox object
# this =
#   hammer:true
#   flashlight:false

# Run a method with a callback
Meteor.call "use_hammer", ->
  console.log this

In this case, the this object will return a top-level object such as the browser window. This is not useful at all. Let's bind this now:

#COFFEESCRIPT
# Let's make the context of this equal to our toolbox object
# this =
#   hammer:true
#   flashlight:false

# Run a method with a callback
Meteor.call "use_hammer", =>
  console.log this

The key difference is the use of => instead of the expected -> to define the function. Using => will make the callback's this object equal to the context of the executing function. The resulting compiled script is as follows:

//JAVASCRIPT
Meteor.call("use_hammer", (function(_this) {
  return function() {
    return Console.log(_this);
  };
})(this));

CoffeeScript will improve your coding quality and speed. Still, CoffeeScript is not flawless. When you start combining functions with nested arrays, things can get complex and difficult to read, especially when the functions are constructed with multiple parameters. Let's look at a common query that does not look as readable as you would expect it to be:

#COFFEESCRIPT
People.update
  sibling:
    $in:["bob","bill"]
,
  limit:1
  ->
    console.log "success!"

This collection query is passing three parameters: the filter object, the options object, and the callback function. To differentiate between the first two objects, we had to place a comma at the same level as the function and then, indent the second parameter. This is unwieldy, but we can use variables in order to make the query more readable:

#COFFEESCRIPT
filter =
  sibling:
    $in:["bob","bill"]
options =
  limit:1
People.update filter, options, ->
  console.log "success!"

Go to coffeescript.org and play around with the language by clicking on the "try coffeescript" link.

Jade for Meteor

Jade works much like CoffeeScript but it is used for HTML instead. I recommend that you install the mquandalle:jade package. All the Jade files are saved with a .jade extension. This section will cover the most used aspects of Jade in Meteor such as HTML tags, components, and helpers.

HTML tags

Much like CoffeeScript, Jade is a language that depends heavily on tabbing. When you want to add children to an HTML tag, you simply use tab. Tag IDs and classes can be added using the CSS selector notation ('input#name.first'). This means classes are expressed with a dot (.) and IDs are expressed with a pound (#). Let's look at an example:

//- JADE
div#container
  ul.list
    li(data-bind="clickable") Click me!

<!-- HTML – OUTPUT -->
<div id="container">
  <ul class="list">
    <li data-bind="clickable">Click me!</li>
  </ul>
</div>

As you can see, special attributes such as data-bind are added with parenthesis. Symbols such as <, >, and closures are not required anymore. In this example, we have a div tag with an id attribute of "container", a ul tag with a class attribute of list, and a li tag with a special attribute of data-bind.

You will find yourself using special attributes often for the input tags to add value, placeholder, and other attributes.

Templates and components

Meteor templates are Jade components. In Meteor, we define a template with the template tag and apply the special name attribute to create a reusable HTML block. In Jade, when we create a template, we create a component as well. This looks as follows:

//- JADE
template(name="landing")
  h3 Hello World!

<!-- HTML – OUTPUT -->
<template name="landing">
  <h3>Hello World!</h3>
</template>

Now we can use this template as a Jade component anywhere in our views. To call a Jade component, you simply prepend a plus sign to the name of the template. Let's look at an example where we want to place a landing page inside a main_layout page:

//- JADE
template(name="landing")
  h3 Hello World!

template(name="main_layout")
  +landing

<!-- HTML – OUTPUT -->
<template name="landing">
  <h3>Hello World!</h3>
</template>

<template name="main_layout">
  {{> landing}}
</template>

That's it! Notice that we have prepended the plus (+) sign to the name of the template to call it. This is equivalent to using {{> landing}} in SpaceBars (Meteor's version of Handlebars). Components can have parameters as well, which can be later used in the templates' instance. Let's make our example output someone's name:

//- JADE
template(name="landing")
  h3 Hello {{name}}

template(name="main_layout")
  +landing(name="Mr Someone")

# COFFEESCRIPT
Template.landing.helpers
  "name": ->
    Template.instance().data.name

<!-- HTML – OUTPUT -->
<template name="landing">
  <h3>Hello {{name}}</h3>
</template>

<template name="main_layout">
  {{> landing name="Mr Someone"}}
</template>

Adding attributes to your templates can make your templates flexible as shown in the preceding example. Still, it is unlikely that you will have to use this as templates "soak up" data from their parent context.

Helpers

Helpers in Meteor are functions that return data before rendering to the view. We use helpers for iteration, logical statements, and variables. The two basic helpers are each and if, but adding the raix:handlebar-helpers package will add a dictionary of other useful helpers to keep your code from repeating. Let's have a look at how we can use our helpers:

//- JADE
template(name="list_of_things")
  each things
    if selected
      p.selected {{name}}
    else
      p {{name}}

<!-- HTML – OUTPUT -->
<template name="list_of_things">
  {{#each things}}
    {{#if selected}}
      <p class="selected">{{name}}</p>
    {{else}}
      <p>{{name}}</p>
    {{/if}}
  {{/each}}
</template>

In this example, the each helper is iterating through the return value of another helper named things and if the selected helper resolves to true, then we will render p.selected with the name variable.

It's important to understand that everything that is not an HTML tag is a helper, and that if you want to use a helper within a tag, you need to use {{}} or #{} to express this.

Go to jade-lang.com and handlebars.js to know more specific information. With this information, you should be able to do just about anything.

Stylus for Meteor

Stylus works much like CoffeeScript and Jade but it is for CSS. I recommend that you install mquandalle:stylus. This package is preinstalled with useful tools such as Jeet and Rupture. All Stylus files are saved with a .styl extension. There are only three things that we need to learn about Stylus: CSS tags, variables, and functions.

CSS tags

Stylus is a language that does away with the need for semicolons (;) and curly braces ({}) in exchange for making good use of tabbing. Let's look at an example:

// STYLUS
// Let's make a vertical positioning class
.vertical-align-middle
  //PART 1
  position:absolute
  width:100%
  height:100%
  display:table
  overflow-x:hidden

  .special
    background:black

We can see in PART 1 how properties are defined for a class by tabbing those properties in .special is used to select an HTML tag with the special class that is a child of the vertical-align-middle class. Let's look at how PART 1 compiles:

/* CSS – OUTPUT PART 1 */
.vertical-align-middle {
  position:absolute;
  width:100%;
  height:100%;
  display:table;
  overflow-x:hidden;
}
.vertical-align-middle .special {
  background:black;
}

Now let's add a more complex selector:

// STYLUS
// Let's make a vertical positioning class
.vertical-align-middle
  //PART 1
  ...

  //PART 2
  > *
    display:table-cell
    vertical-align:middle

PART 2 has a combination of special CSS2 selectors: specific parent (>) and all elements (*). In this particular order, the CSS2 selectors are picking the "any first sibling" element only and applying the rules. Let's look at how PART 2 compiles:

/* CSS – OUTPUT PART 2 */
.vertical-align-middle > * {
  display:table-cell;
  vertical-align:middle;
}

Let's add a new class to the current class that aligns the object to the top:

// STYLUS
// Let's make a vertical positioning class
.vertical-align-middle
  //PART 1
  ...
  //PART 2
  ...
  //PART 3
  &.whole-page
    top:0

PART 3 uses an ampersand (&) to describe an element that is not a child but instead is concatenated with the extra class. Let's look at how PART 3 compiles:

/* CSS – OUTPUT PART 3 */
.vertical-align-middle.whole-page {
  top:0;
}

Variables

Unlike CSS, Stylus supports variables. This keeps a lot of things manageable when we want to make major changes to the look of our site. Suppose we have two colors that we want to use throughout our site, but we know that these colors are going to change. Let's define them as variables so that we can easily modify them later:

// STYLUS
primary-color = #ffffff
$secondary-color = #333333

.text-default
  color:primary-color
  background:$secondary-color

.text-inverted
  color:$secondary-color
  background:primary-color

Easy right? In this example, both primary-color and $secondary-color are variables. Stylus optionally supports the use of the money sign ($) to indicate a variable. This can make it easier to spot variables.

Functions/mixins

Unlike CSS, Stylus supports functions too. LESS, Stylus, and Sassy CSS (SCSS) refer to functions as mixins. Functions will make your CSS concoctions much easier to share across a project. We will cover the two types of mixins in Stylus: mixins and transparent mixins.

Mixins are functions that take a defined set of parameters. Let's take a look at how we can write a mixin:

// STYLUS
animation(duration,delay,timing)
  -webkit-animation-duration:duration
  animation-duration:duration
  -webkit-animation-delay:delay
  animation-delay:delay
  -webkit-animation-timing-function:timing
  animation-timing-function:timing

button
  animation(500ms,0,ease-out)

/* CSS – OUTPUT */
button {
  -webkit-animation-duration:500ms;
  animation-duration:500ms;
  -webkit-animation-delay:0;
  animation-delay:0;
  -webkit-animation-timing-function:ease-out;
  animation-timing-function:ease-out;
}

In this example, we first define the animation mixin, and then we apply the mixin to the button HTML tag. However, there is a much easier and effective way of doing this via a transparent mixin.

A transparent mixin, basically, takes all the parameters and saves them in an arguments variable without you having to define anything. Let's have a look:

// STYLUS
animation()
  -webkit-animation:arguments
  animation:arguments

button
  animation(pulse 3s ease infinite)

/* CSS – OUTPUT */
button {
  -webkit-animation:pulse 3s ease infinite;
  animation:pulse 3s ease infinite;
}

Notice how we did not have to define every single parameter in the mixin, and the arguments variable simply passed all the arguments that it could find. This is especially useful for keeping the code flexible.

Stylus essentially upgrades CSS in such a way that it makes the code much easier to manage and therefore, ends up saving us a lot of development time.

Go to stylus-lang.com and learnboost.github.io/stylus to learn more about Stylus.

Templates, helpers, and events

Now that we are on the same page for the languages that we are going to use throughout the book, let's do a quick review of some of the elements that we will use during our development process.

Templates, helpers, and events are used to build the frontend of your application. Using them effectively is the key to how we design our backend as well (which we will address in Chapter 2, Publish and Subscribe Patterns).

Templates

Meteor templates are the special blocks of HTML code that generate Meteor template objects (Template.<yourtemplate>). It is through Meteor template objects that we wire the HTML code to logic. People who have worked with an MVC framework will refer to these templates as views. This is a key concept to understand.

Open up your terminal and create a new project:

meteor create basic_meteor

Now let's add our languages:

meteor add coffeescript
meteor add mquandalle:jade
meteor add mquandalle:stylus

Remove the three visible files from /basic_meteor (do not remove any of the files starting with a dot), and create /client/layout.jade. This is something that exists in one way or another in every Meteor project. Let's program:

//- layout.jade
head
  title Meteor Basics
  meta(name="viewport" content="user-scalable=no, initial- scale=1.0, maximum-scale=1.0")
  meta(name="apple-mobile-web-app-capable" content="yes")
body
  +basic_template

I highly recommend adding these metatags to make your site mobile-friendly right from the beginning. With this snippet of code, we are effectively starting up the very first thing that Meteor is going to render before running any code. Once this is rendered, Jade takes care of rendering basic_template. Let's program this in a new file, /client/basic_template.jade:

//- basic_template.jade
template(name="basic_template")
  h1 Hello World!

Behind the scenes, Meteor is compiling our Jade templates and putting them all in one big file. You will never have to worry about loading basic_template.jade before layout.jade when it comes to templating.

Throughout the book, we will use meteorhacks:flow-router and meteorhacks:flow-layout to easily navigate to different templates.

Creating helpers

We have already discussed what helpers are in Jade, but how do we create helpers in Meteor? Let's go back to our basic_meteor project and create /client/basic_template.coffee. It is important to understand that Meteor helpers are used to control the variables in our template. People who have worked with an MVC framework can view this file as a controller. Let's write our first helper:

#basic_template.coffee
Template.basic_template.helpers
  "name": ->
    "Mr Someone"

Notice that the helper is defined within the helpers function of the Meteor template object: Template.<your_template>.helpers(<your_helpers>). Helpers are mostly functions that will return anything you want them to including Meteor collection cursors. Let's bring all this together now:

//- basic_template.jade
template(name="basic_template")
  h1 Hello {{name}}

This will output Hello Mr Someone inside the h1 HTML tag. Let's add a slightly more complex helper:

#basic_template.coffee
Template.basic_template.helpers
  "person": ->
    name:"Someone"
    prefix: "Mr"
    children: [
      {
        name:"Billy"
      }
      {
        name:"Nancy"
      }
    ]

//- basic_template.jade
template(name="basic_template")
  with person
    h1 Hello {{prefix}} {{name}}

    ul
      each children
        li {{name}}

In this example, we are using with to set up the data context of the HTML tags that belong to it; this data context is equivalent to person. Data context refers to the value of this inside a helper. So if you set up an object as the data context, this will be equivalent to that object. Also, we iterate through children with an each statement so that we can list out their names.

Events

Meteor taps into common JavaScript HTML events such as click, change, and focus. An event is anything that happens to an HTML element that you are listening to. Suppose we want to be able to change the name of a person to one of the children by clicking on them. We do this through the templates' event map. Let's take a look at an example of how we can do this without using reactivity or collections:

#basic_template.coffee
Template.basic_template.events
  "click li": ->
    $("h1").text "Hello #{@name}"

Easy! So to catch template events, we need to use the Template.<your_template>.events(<your_event_map>) function. In this particular example, we are using jQuery to replace text.

The event map is an object where the properties specify a set of events to be handled. These events may be specified in any of the following ways:

# Runs any time you click anywhere
"click": ->

# Runs any time you click a li element
"click li": ->

#Runs any time you click a li element OR mouseover a li element
"click li, mouseover li": ->

The key string of the event is composed of two parts: the first is always a type of event (click, hover, change, and so on) while the second is always a CSS selector.

The event loop and the merge box

Before diving into Meteor, it is critical to understand what the event loop and the merge box are and how they can adversely affect your code. Both are relatively complex in the way that they were programmed, so we will focus on understanding the general concept.

The event loop

The event loop is like a queue; it runs a series of functions one by one. Because functions are processed sequentially, each function effectively blocks others from being processed until the function is done.

In other words, the event loop functions much like a single-line conveyor belt where things are being inspected. For every inspection made, the line is stopped and nothing moves.

Meteor uses Fibers – a NodeJS library – to get around this issue. Many of the functions that you will run will be on a separate fiber. What does this mean? This means that the functions will run on a separate conveyor belt for processing. Still, not all functions are built this way, you need to make sure your server-side functions do not block the server.

So which functions could potentially cause the server to get blocked? Meteor.methods(), Meteor.publish(), and any function that does not run inside a fiber on the server. Let's see how we can unblock each one and when we should do this.

Functions defined under the Meteor.methods() that you know are going to take a long time to process, should always run on a Fiber or defer time consuming code to a Fiber. We can quickly solve this by calling the @unblock() function from within the method. Let's look at an example:

# METEOR METHODS
Meteor.methods
  #BLOCKING
  time_consuming: ->
    Meteor.setTimeout ->
        console.log "done"
      ,60000

  #NON-BLOCKING
  time_consuming_unblock: ->
    @unblock()
    Meteor.setTimeout ->
        console.log "done"
      ,60000

In this example, when you run Meteor.call("time_consuming"), the server will be blocked. When the server is blocked, other visitors won't be able to reach your site! Instead if you run Meteor.call("time_consuming_unblock"), the server will continue to function properly but consume more resources to do so.

Meteor.publish() can be easily unblocked after installing the meteorhacks:unblock package as well. This one will be particularly useful when we start to make very complex publishers that might consume a lot of resources. Let's look at an example:

# METEOR PUBLISH
#BLOCKING
Meteor.publish "external_API_query", ->
  HTTP.get "http://connect.square.com/payments"

#NON-BLOCKING
Meteor.publish "external_API_query_unblocked", ->
  @unblock()
  HTTP.get "http://connect.square.com/payments"

In this example, we are waiting for an HTTP call to respond. This will certainly block the server if we subscribe to external_API_query, so we use external_API_query_unblocked instead.

All other functions that run on the server and you know are going to block the server, should run on a fiber. Meteor has a special function to help us make this easy. It is called Meteor.wrapAsync(). Let's see how this works:

# METEOR UNBLOCKED FUNCTION
unblock_me = Meteor.wrapAsync ->
  Meteor.setTimeout ->
      console.log "done"
    ,60000

Tip

It is very important to keep the event loop in mind, especially when we're connecting our web application to external services that are going to cause massive delays to our server.

The merge box

The merge box is the algorithm that identifies all the changes that are happening to the database. It basically handles publishers, subscribers, and reactivity. The merge box also handles the initial load of data using DDP messages.

It is important to understand that we can communicate directly with the merge box via all the commands that are available to us under the Meteor.publish() function. The more optimal we can make our Meteor.publish functions, the faster the site will load.

The beginning of our online shop

Throughout the book we will be developing an e-commerce website to help us understand the core concepts of advanced Meteor web development. Let's begin by creating a new project:

meteor create online_shop

The must-have packages

Atmospherejs.com has always been the "go to" website to find packages. Here you will find thousands of packages produced by the community for free. There are a handful of packages that we absolutely need to install to make our website function properly.

First, we install the languages:

meteor add coffeescript
meteor add mquandalle:jade
meteor add mquandalle:stylus
meteor add less

Next, the router and functions that will help us with SEO and routing:

meteor add kadira:flow-router
meteor add kadira:blaze-layout
meteor add meteorhacks:fast-render
meteor add nimble:restivus
meteor add yasinuslu:blaze-meta
meteor add dfischer:prerenderio
meteor add wizonesolutions:canonical

Note

WARNING: Do not run Meteor yet! Canonical could mess up your project unless you have it set up correctly.

We will need a couple of packages as well to help us manage publishers:

meteor add lepozepo:publish-with-relations
meteor add tmeasday:publish-counts
meteor add meteorhacks:aggregate
meteor add http
meteor add meteorhacks:unblock

These next packages will extend Meteor's functions:

meteor add xorax:multiple-callbacks
meteor add aldeed:collection2
meteor add aldeed:autoform
meteor add fastclick
meteor add reactive-var
meteor add alanning:roles
meteor add accounts-password
meteor add u2622:persistent-session
meteor add ongoworks:security

We will need these packages to properly manage time:

meteor add momentjs:moment
meteor add mrt:moment-timezone

For the last set, we'll be using a couple of additional packages that will make the design process much faster:

meteor add kyleking:customizable-bootstrap-stylus
meteor add raix:handlebar-helpers
meteor add fortawesome:fontawesome
meteor add percolate:momentum

We need to remove some packages for security too:

meteor remove autopublish
meteor remove insecure

All of these packages will be explained in more detail throughout the book, but all of these are must-haves. The first package that we need to explain is the wizonesolutions:canonical package. This package makes sure that all incoming traffic is routed to your ROOT_URL, so it is particularly useful when you want all the traffic to go to your SSL site. The first thing that we need to do before running Meteor is set up canonical to run only in the production environment.

Create /server/canonical.coffee, and add this code:

#/server/canonical.coffee
if process.env.NODE_ENV is "development" or process.env.ROOT_URL.indexOf("meteor.com") > -1
  Meteor.startup ->
    process.env.PACKAGE_CANONICAL_DISABLE = true

This code snippet effectively sets your PACKAGE_CANONICAL_DISABLE environment variable to make sure that canonical is inactive while you are developing.

What are environment variables? These variables are defined within the scope of the deployment, and they make sure that the project knows information before the build finishes on the server. Information such as what database to use, which domains to use, and other setup information can usually be found in these variables. We will cover this information in the final chapter.

File structure

A proper file structure is tremendously important in Meteor. We have found that the best way to work is with functional top-level modules. This means that every folder is a micro-service, and therefore can act on its own. This allows for a lot of modularity in the project, and it's very easy for others to understand what it is that you are trying to accomplish. In this section, we will cover this file structure and Meteor's special folders.

Let's look at a sample web application folder structure:

/online_shop
/online_shop/cart
/online_shop/cart/cart_route.coffee  #RUNS ON CLIENT AND SERVER
/online_shop/cart/client
/online_shop/cart/client/cart_view.jade  #RUNS ON CLIENT ONLY
/online_shop/cart/client/cart_controller.coffee
/online_shop/cart/client/cart.styl
/online_shop/cart/server
/online_shop/cart/server/cart_publisher.coffee  #RUNS ON SERVER ONLY
/online_shop/cart/server/cart_methods.coffee

In this folder structure, cart is the micro-service, and it is composed of a route, view, controller, and publisher. The files placed under a /client directory will be published to the client and will only run on the client. The files placed under a /server directory will only run and be accessible on the server. If a file is placed in none of these directories, then the file will run on both the client and server. The expected structure goes like this:

/project_folder
/project_folder/_globals
  ./client/<global support function files>
  ./server/<global support function files>
  ./lib/collections/<collection>/<file>
  ./lib/collections/<collection>/server/<permissions file>

/project_folder/router
  ./client/layouts/<layout file>
  ./lib/<configuration file>
  ./lib/<middleware file>

/project_folder/<module>
  ./<route file>
  ./client/<template file>
  ./client/<logic file>
  ./client/<styles file>
  ./server/<publishers file>
  ./server/<methods file>

It's important to note that the /lib directory will always run before any other code does. Let's place our canonical file under the /_globals/canonical/server directory.

Let's create our first module: the router. Create the /router/client/layout.jade directory, and we will only have one layout throughout the project. Now let's code our layout:

//- LAYOUT.JADE
head
  title Online Shop
  meta(charset="utf-8")

  //- Allow saving to homescreen
  meta(name="apple-mobile-web-app-capable" content="yes")

  //- Do not try to detect phone numbers
  meta(name="format-detection" content="telephone=no")

  //- Make it mobile friendly
  meta(name="viewport" content="user-scalable=no, initial- scale=1.0, maximum-scale=1.0")

body

template(name="layout")
  +Template.dynamic(template=nav)
  +Template.dynamic(template=content)

Here, we have introduced the Template.dynamic component. This component may be used to render other templates dynamically by changing the value of a variable to the name of the template we want to render. We decided to use two variables—nav and content— that are controlled by the router. So, basically, the content variable will be changing to different strings that are equal to the names of our templates.

We will create our landing module in the next chapter to learn not only how to use the router but also how to properly subscribe to data.

Summary

We have addressed a lot of things in this chapter. We can now program faster because we have tools such as CoffeeScript, Jade, and Stylus to help us. Also, we have learned how to use templates, helpers, and events to work with our Meteor frontend. Understanding the event loop and the merge box has made us a bit more precautious when it comes to running complex, time-consuming operations. Finally, we began to build a project, and we adopted a folder structure that is going to make development quicker.

In the next chapter, we will cover two of the most important parts that make a Meteor application viable: Meteor publishers and Meteor subscribers. With these patterns, you will be able to produce sites that load quickly and that do not put too much strain on the server.

Left arrow icon Right arrow icon
Download code icon Download Code

Description

With the increasing interest in NodeJS web applications, a new framework, Meteor, has joined the ranks to simplify developer workflows. Meteor is one of the few open source frameworks that has received funding since its early development stages. It builds on ideas from existing frameworks and libraries, offering developers an easy way to develop a prototype app. At the same time, it gives them the tools and flexibility to build a fully fledged production app. Meteor is the weapon of choice for start-ups in today’s world. Meteor Design Patterns cuts through the jargon that most websites play with and gets to the point with simple solutions that will boost your development skills. We start off with a refresher on the basics of JavaScript programming such as templates, CoffeeScript, the Event Loop, and the Merge Box, amongst others. You then learn how to map real-world data and optimize the data’s publishers to output data with the least amount of work done by the server with some subscribe and publish patterns. Next, using front-end patterns, you will learn how to create maintainable and trackable forms, and make our site crawlable by any search engine. Following this, you will see how to optimize and secure the web application and maintain applications without breaking other features. Finally, you will learn how to deploy a secure production-ready application while learning to set up modulus, compose with Oplog tracking and SSL certificates, as well as error tracking with Kadira. Throughout the book, you will put your skills to practice and build an online shop from scratch. By the end of the book, you will have built a feature-rich online shop.

Who is this book for?

This book is for developers who have already had an introductory course with Meteor. Basic knowledge of web development is recommended.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 21, 2015
Length: 184 pages
Edition : 1st
Language : English
ISBN-13 : 9781783987627
Vendor :
Meteor Development Group
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Oct 21, 2015
Length: 184 pages
Edition : 1st
Language : English
ISBN-13 : 9781783987627
Vendor :
Meteor Development Group
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 109.97
Meteor Design Patterns
$38.99
Meteor Cookbook
$43.99
Building Single-page Web Apps with Meteor
$26.99
Total $ 109.97 Stars icon
Banner background image

Table of Contents

7 Chapters
1. Getting Started with Meteor Chevron down icon Chevron up icon
2. Publish and Subscribe Patterns Chevron down icon Chevron up icon
3. Front-end Patterns Chevron down icon Chevron up icon
4. Application Patterns Chevron down icon Chevron up icon
5. Testing Patterns Chevron down icon Chevron up icon
6. Deployment Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(6 Ratings)
5 star 50%
4 star 33.3%
3 star 0%
2 star 16.7%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




rsundar Nov 19, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A very useful resource to take your meteor skills to the next level. Shows you how you can deploy your meteor applications in a production setting and use Kadira to enhance it's performance. All in all definitely recommended for someone who has a good grasp on the basics of the meteor framework.
Amazon Verified review Amazon
James Coles Oct 28, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I had this book on preorder the moment I saw it on Amazon. It arrived and I read it within the day. I've got 4 books on Meteor in total and this one is by far the best one I have read so far. It's the story told from start to end. It's not a lose collection of recipes it as the cookbooks and it's not a half hearted approach to explain a few features or modules as other books on the market. This is a reference and a milestone book for meteor. If you want to get serious about this framework. Get this book.If I have one concern it is that the book is using coffeescript, stylus and jade, but it's simple enough to translate this to javascript, scss and html templates when needed.
Amazon Verified review Amazon
Lars Lemos Dec 04, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I come from a Java EE background so was looking for a fast paced recipes book.Found exactly what I needed.This book contains this most fundamentals instructions from how to set up your development environment from scratch to the introduction to the Front-end patterns and Application patterns, it also include testing Patterns and the most important how to deploy our app to the cloud services.Although being a small book, the author was able to compact all the necessary information for the best understanding of the reader.I advice to read this book along with some other reference book or documentation to make the most out of the content that the patterns describe.What fascinated me more in this book was the fact that I was not expecting to find instruction on how to put my app in production since by the name "Meteor Design Patterns", so you get more than you expected.The book is worth reading and future reference.
Amazon Verified review Amazon
Kevin Nicholas Casault Nov 24, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Let me start by saying I am not a Meteor expert just someone in the process of learning Meteor. Also just to be clear when you read design patterns in the title think reusable solutions or good practices not along the concept of the Gang of 4 design patterns. I feel like the advice in the beginning of the book about using JavaScript (Coffee) and CSS (Stylus) preprocessors and HTML (Jade) template engines could probably be used with any modern JavaScript framework. Probably good advice in general. From Chapter 2 on the book is much more Meteor specific in the solutions it presents. The different types of variables available to Meteor applications was a good discussion for example. As someone learning Meteor, many of the patterns were very helpful as I think about building Meteor applications and what needs to be done to make a Meteor application search engine friendly.The product order/shopping cart example used through out the book is helpful and easy to understand as the features are added to it through out the book.The book has been a good learning tool and I can see it being a good tool to refer to in the future as well. The design patterns presented should be helpful even as Meteor matures and changes of time.There are also many atmosphere packages discussed and recommended in the book to help solve specific problem this is a nice add because searching through packages can be a time consuming.
Amazon Verified review Amazon
eskadah Nov 20, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
At the time of writing, this book is one of the few advanced level books on Meteor that are available on the market. This book guides the reader on a number of best practices for real world meteor development.Furthermore, the author of the book has a number of open source meteor packages that I have found very useful in my own work. So he definitely knows what he is talking about. For instance, the author does a good jobexplaining the importance of reactive joins in Meteor projects, the author illustrates the problem from a UI /UX perspective but ultimately breaks down the technical DDP aspects of the problem and mostimportantly provides practical solutions to implementing reactive joins in Meteor. I am giving this book 4 stars for a number of reasons. Given the fact that the code samples are in CoffeeScript,the editing could be better. Its a bit of a chore to read and understand a code sample given the liberal use of tabs, lack of commas and absent parentheses. This point brings me to my second gripe with the book.The book is very opinionated. The author tries to mitigate this in the first chapter but one chapter to introduce Coffeescript, Jade and Stylus is not enough. Readers that are not already versed in these technologies will not be able to gain much from this book.All in all, its a very good intermediate/advanced level book on Meteor. Beginners to the Meteor framework should probably look elsewhere for an introduction but they should definitely come back once they are looking for more advanced knowledge
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.