Boilerplates and generators

On a MEAN stack environment, our ecosystem is infinitely diverse, and we can find excellent alternatives to start the construction of our API. At hand, we have simple boilerplates to complex code generators that can be used with other tools in an integrated way, or even alone.

Boilerplates are usually a group of tested code that provides the basic structure to the main goal, that is to create a foundation of a web project. Besides saving us from common tasks such as assembling the basic structure of the code and organizing the files, boilerplates already have a number of scripts to make life easier for the frontend.

Let's describe some alternatives that we consider as good starting points for the development of APIs with the Express framework, MongoDB database, Node server, and AngularJS for the frontend.

Some more accentuated knowledge of JavaScript might be necessary for the complete understanding of the concepts covered here; so we will try to make them as clearly as possible.

It is important to note that everything is still very new when we talk about Node and all its ecosystems, and factors such as scalability, performance, and maintenance are still major risk factors. Bearing in mind also that languages such as Ruby on Rails, Scala, and the Play framework have a higher reputation in building large and maintainable web applications, but without a doubt, Node and JavaScript will conquer your space very soon.

That being said, we present some alternatives for the initial kickoff with MEAN, but remember that our main focus is on SPA and not directly on MEAN stack.

Hackathon starter

Hackathon is highly recommended for a quick start to develop with Node. This is because the boilerplate has the main necessary characteristics to develop applications with the Express framework to build RESTful APIs, as it has no MVC/MVVM frontend framework as a standard but just the Bootstrap UI framework. Thus, you are free to choose the framework of your choice, as you will not need to refactor it to meet your needs.

Other important characteristics are the use of the latest version of the Express framework, heavy use of Jade templates and some middleware such as Passport—a Node module to manage authentication with various social network sites such as Twitter, Facebook, APIs for LinkedIn, GitHub, Last.fm, Foursquare, and many more.

They provide the necessary boilerplate code to start your projects very fast, and as we said before, it is very simple to install; just clone the Git open source repository:

git clone --depth=1 https://github.com/sahat/hackathon-starter.git myproject

Run the NPM install command inside the project folder:

npm install

Then, start the Node server:

node app.js

Note

Remember, it is very important to have your local database up and running, in this case MongoDB, otherwise the command node app.js will return the error: Error connecting to database: failed to connect to [localhost: 27017]

You can check for more details at: https://github.com/sahat/hackathon-starter

MEAN.io or MEAN.JS

This is perhaps the most popular and currently available boilerplate. MEAN.JS is a fork of the original project MEAN.io; both are open source, with a very peculiar similarity, both have the same author. You can check for more details at http://meanjs.org/.

However, there are some differences. We consider MEAN.JS to be a more complete and robust environment. It has a structure of directories, better organized, subdivided modules, and better scalability by adopting a vertical modules development.

To install it, follow the same steps as previously:

  1. Clone the repository to your machine:
    git clone https://github.com/meanjs/mean.git
    
  2. Go to the installation directory and type on your terminal:
    npm install
    
  3. Finally, execute the application; this time with the Grunt.js command:
    grunt
    
  4. If you are on Windows, type the following command:
    grunt.cmd
    

Now, you have your app up and running on your localhost.

The most common problem when we need to scale a SPA is undoubtedly the structure of directories and how we manage all of the frontend JavaScript files and HTML templates using MVC/MVVM. Later, we will see an alternative to deal with this on a large-scale application; for now, let's see the module structure adopted by MEAN.JS:

MEAN.io or MEAN.JS

Note that MEAN.JS leaves more flexibility to the AngularJS framework to deal with the MVC approach for the frontend application, as we can see inside the public folder. Also, note the modules approach; each module has its own structure, keeping some conventions for controllers, services, views, config, and tests. This is very useful for team development, so keep all the structure well organized. It is a complete solution that makes use of additional modules such as passport, swig, mongoose, karma, among others.

The Passport module

Some things about the Passport module must be said; it can be defined as a simple, unobtrusive authentication module. It is a powerful middleware to use with Node; it is very flexible and also modular. It can also adapt easily within applications that use the Express.

It has more than 140 alternative authentications and support session persistence; it is very lightweight and extremely simple to be implemented. It provides us with all the necessary structure for authentication, redirects, and validations, and hence it is possible to use the username and password of social networks such as Facebook, Twitter, and others.

The following is a simple example of how to use local authentication:

var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
User = require('mongoose').model('User'),

module.exports = function() {
// Use local strategy
passport.use(new LocalStrategy({
  usernameField: 'username',
  passwordField: 'password'
},
function(username, password, done) {
  User.findOne({
    username: username
  },
function(err, user) {
  if (err) {
  return done(err);
  }
  if (!user) {
    return done(null, false, {
    message: 'Unknown user'
    });
  }
  if (!user.authenticate(password)) {
    return done(null, false, {
    message: 'Invalid password'
    });
  }
return done(null, user);
});
}
));
};

Here's a sample screenshot of the login page using the MEAN.JS boilerplate with the Passport module:

The Passport module

Back to the boilerplates topic; most boilerplates and generators already have the Passport module installed and ready to be configured. Moreover, it has a code generator so that it can be used with Yeoman, which is another essential frontend tool to be added to your tool belt.

Note

Yeoman is the most popular code generator for scaffold for modern web applications; it's easy to use and it has a lot of generators such as Backbone, Angular, Karma, and Ember to mention a few. More information can be found at http://yeoman.io/.

Generators

Generators are for the frontend as gem is for Ruby on Rails. We can create the foundation for any type of application, using available generators.

Here's a console output from a Yeoman generator:

Generators

It is important to bear in mind that we can solve almost all our problems using existing generators in our community. However, if you cannot find the generator you need, you can create your own and make it available to the entire community, such as what has been done with RubyGems by the Rails community.

RubyGem, or simply gem, is a library of reusable Ruby files, labeled with a name and a version (a file called gemspec).

Tip

Keep in mind the Don't Repeat Yourself (DRY) concept; always try to reuse an existing block of code. Don't reinvent the wheel.

One of the great advantages of using a code generator structure is that many of the generators that we have currently, have plenty of options for the installation process. With them, you can choose whether or not to use many alternatives/frameworks that usually accompany the generator.

The Express generator

Another good option is the Express generator, which can be found at https://github.com/expressjs/generator.

In all versions up to Express Version 4, the generator was already pre-installed and served as a scaffold to begin development. However, in the current version, it was removed and now must be installed as a supplement.

They provide us with the express command directly in terminal and are quite useful to start the basic settings for utilization of the framework, as we can see in the following commands:

  create : .
  create : ./package.json
  create : ./app.js
  create : ./public
  create : ./public/javascripts
  create : ./public/images
  create : ./public/stylesheets
  create : ./public/stylesheets/style.css
  create : ./routes
  create : ./routes/index.js
  create : ./routes/users.js
  create : ./views
  create : ./views/index.jade
  create : ./views/layout.jade
  create : ./views/error.jade
  create : ./bin
  create : ./bin/www

  install dependencies:
    $ cd . && npm install

  run the app:
    $ DEBUG=express-generator ./bin/www

Very similar to the Rails scaffold, we can observe the creation of the directory and files, including the public, routes, and views folders that are the basis of any application using Express.

Note the npm install command; it installs all dependencies provided with the package.json file, created as follows:

{
  "name": "express-generator",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "express": "~4.2.0",
    "static-favicon": "~1.0.0",
    "morgan": "~1.0.0",
    "cookie-parser": "~1.0.1",
    "body-parser": "~1.0.0",
    "debug": "~0.7.4",
    "jade": "~1.3.0"
  }
}

This has a simple and effective package.json file to build web applications with the Express framework.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.47.218