MEANJS Demo Application

Standard

Sometime ago I started developing manually the following application with the MEAN stack.

When I started developing this application there didn’t exist some Yeoman generators that exist nowadays, and frameworks didn’t offer the facilities that currently they offer. As we have seen in previous articles, for developing our projects it’s very convenient to choose those tools that better fit to our projects features. If I had to start developing this application nowadays, I didn’t do it from scratch, and I would choose some tools that help me developing the project.

In next articles I will explain how to develop this application with mean.js.

Demo ApplicationGitHub

REST API Development with Sails.js

Standard

In the previous article I explained how develop a REST API with MongoDB, NodeJS and Express from scratch. We saw that developing an API from scratch is a simple process although it could be quite tedious. We have also written in previous articles that when we have to develop a new project is very important to know and to analyze which tools are the best for our project.

Productivity is a very important factor in the software development process. For this reason, taking productivity into account, in this article I would like to introduce the Sails.js framekork, which will easy and expedite the REST API development process.

 

Sails.js description

Based on the official Sails.js website:

Sails.js make it easy to build custom, enterprise-grade Node.js apps. It is designed to mimic the MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with scalable, service-oriented architecture. It’s especially good for building chat, realtime dashboards, or multiplayer games.

 

One of the things that Sails.js provides us, among many other, is the REST API development easily and quickly. For this reason, I consider that Sails.js is a very important tool in the software stack that I explained in the article modern web applications development.

 

Developing an API with Sails.js

In this article I had planned to write some sections to explain how to develop an API with Sails.js, but as the process is so easy and so fast I’m going to explain it in only one section. Running solely a couple of commands and writing solely a line of code we will be able to develop the same API that we developed in the article API REST Development with MongoDB, NodeJS and Express, but with more features:

As we can see, at first place we generate our project running the command  sails generate new MyApi –no-front-end and, after that, we generate our API for the Message entity running the command sails generate api message.

Finally, we have to define our entity properties, which only has the text property. For this, we have to edit the file api/models/Message.js and define its properties in this way:

 

Sails.js Database

Sails.js works with the Waterline ORM, which is developed and maintained by the Sails.js development team.

Waterline has adapters to connect to some databases (MySQL, PostgreSQL and MongoDB, among others). Also we can configure Waterline to save our data in disk or in memory (it isn’t recommended for production), so we could test our applications without the need of running a database in our workstation.

By default, Sails.js is configured to use the local disk adapter (save the data in a temporary folder of our file system). We define our database connections in the file config/connections.js and we define which connection we want to use by default for our entities in the file config/models.js. When we define each of our entities we can specify which connection we want to use. If we don’t specify any connection then Sails.js will use the connection defined by default in the config/models.js file.

 

Testing our API

For testing our API we have to run our application running the following command:

Once we have started our server then we will use a Chrome extension called POSTMAN to send requests to our API.

If we want to get all the messages then we will send a GET request to the URL http://localhost:1337/message:

blog-ch2-empty-collection

If we want to create a new message then we will send a POST request to our API:

blog-ch2-post

And if we send again a GET request to http://localhost:1337/message then we will get the following data:

blog-ch2-collection

 

Models associations with Sails.js

Models associations is another feature that has got Sails.js to generate APIs and that would involve quite work if we had to develop it manually.

To explain models associations we are going to use the same example that use the Sails.js team in the documentation. The example that I’m going to explain is an one to many relationship between Users and Pets, where an user will have got many pets.

At first place, I’m going to generate our API for the Pet entity:

And I’m going to define it as the Sails.js documentation do it:

Next, I’m going to create our API for the User entity:

And I’m going to define it with the following properties:

We are going to start our application with the command sails lift and we are going to test our API with POSTMAN, sending the following requests to our server:

Post request to create an user

blog-ch2-rel-insert-user

 

GET request to get an user list

blog-ch2-rel-list-users-pets-empty

POST request to create a new pet

blog-ch2-rel-insert-pet

 

When we create a new pet we have to introduce the user ID to which the pet belongs.

GET request to get a user list

blog-ch2-rel-list-users-with-pets

Automatically our API returns the pets associated to each user.

GET request to get an user

blog-ch2-rel-list-one-user-with-pets

GET request to get an user’s pet

blog-ch2-rel-list-one-user-one-pet

If we take notice of the URL we see how we associate the models to get the pet which ID equals to 1 of the user which ID equals to 1.

 

Conclusion

In this article we have seen that developing REST APIs with Sails.js is a very simple and a very fast process. Only with a couple of Sails.js commands we are able to create an application structure and an API. From there, we only will have to define our models properties and its associations.

Furthemore, Sails.js offers much more features: realtime notifications, security management, an ORM that will allow us to develop our applications for many databases, and much more.

We have seen that if we choose Sails.js for developing our API instead of developing our API from scratch (as we did in our previous article) we will improve our productivity noticeably.

In next articles we will see more tools that will help us developing our projects.

API REST Development with MongoDB, NodeJS and Express

Standard

In the previous post we analyzed an stack that currently I consider very interesting for developing modern web applications. The front-end of this stack was composed by AngularJS for the browser desktop application, and by Ionic for the mobile application. However, we could choose developing the back-end with some variants, depending on our application requirements.

We also saw the importance of choosing the proper frameworks or tools for developing our projects, because these tools could offer us an important improvement in our productivity and because they could help us developing robust applications.

However, I consider that if you want to get profit from these frameworks it’s convenient that you understand what they do internally. Our back-end will offer us an API that will be in charge of managing and querying our data. In this article we are going to analyze how to create manually a server that will serve a simple API. On subsequent articles we will see how to use some frameworks that will help us developoing our own server much quicker, more robust and with more features.

 

Our Goal

The main goal of this article is developing a simple REST API with NodeJS and Express, so we can see how easy, although tedious, is developing an API in this way. The API will allow to insert new messages in a MongoDB collection and will allow to retrieve a messages list.

You can download the source code from GitHub:

GitHub Source Code

If you want you can clone and start this application running the following commands from the command line:

Next we will explain how to develop an API from scratch.

 

Installing NodeJS packages

The first step is to create a new folder where we are going to develop our project. We have to enter into this folder and we will install the following packages with npm:

  • expressnpm install expressexpress is the most popular web framework for developing web applications in NodeJS.
  • express-generatornpm install -g express-generator. If we don’t have already installed it, we have to install it globally. We will use express-generator to create our application skeleton.
  • mongoosenpm install mongoose –save. Finally, we will install mongoose, that is an ORM that we will use to access our MongoDB database.

In summary, we will run the following commands in our application folder to install the packages that we need:

 

Create the Application

Once we have installed all our packages we have to create our express application. Inside our working folder we will execute the express command and it will create automatically our application skeleton.

Next we have to install the packages that express needs, so we will run npm install from our command line.

Finally, we will start our application running the command npm start.

In summary, from our command line we will execute the following commands for creating and running our web application:

Once our server has started, if we access with our browser to the URL http://localhost:3000 then the application will show us an express welcome page.

Optionally, as we are developing our server to manage an API, we can remove all those files that we don’t need but that has been created by express-generator for delivering web pages: we can remove the public folder content and we can remove the views folder.

 

Connecting to the database

For connecting to the database we are going to create the db folder and inside this folder we will create the index.js file. This file will manage the database connection (we should define the database connection string in a configuration file, but for simplicity and for not extend more the article we will define it directly in the code):

After that we will update the app.js file so it will stablish the connection to the database (lines 7 and 13):

 

Creating the entities

With Mongoose we are going to define our entities schema. For this demo we only define one very simple entity, called Message. In our project folder we will create a folder called models, and we have to create the file message.js inside it:

 

Creating the controllers

In our project folder we will create a folder called controllers, and we have to create the file message.js inside it. Inside the controller we will define the actions that we will be able to execute through our API. In this case, for simplicity, we are going to define only two actions:

  • list: retrive a messages list.
  • create: insert a new message in our messages collection.

 

Creating routes

In our project folder we will create a folder called routes, and we have to create the file message.js inside it. In this file we will define which methods of our controller are going to be executed when our server receives an HTTP request:

 

Finally, we will update the app.js file to add the routes that we have defined in the previous file (lines 6 and 14):

Testing the API

Finally, we have to test that our API works properly. Ideally we would create a test suite, using the superagent package for instance, but as the goal of this article is only developing a simple API, we are not going to explain how to develop these tests.

We are going to test our API manually with a Chrome extension called POSTMAN. The first time that we do a GET of messages, the API will retrieve an empty collection:

blog-ch1-empty-collection

If we want to insert a new message we have to use the POST method and we will send as parameters the message that we want to create:

blog-ch1-post

Finally, if we request the GET method again, then we will get a JSON list that will contain only the message that we have created previously:

blog-ch1-collection

Conclusion

We have seen that creating an API with NodeJS and with Express without an specific framework is a simple although tedious task. There are more features that an API must implement but that we have not explained in this article. Implementing these features manually will take quite time. For example, our API should manage entities relationship, authentication, authorization, etc.

Next articles will explain how to develop an API with frameworks and tools that will improve our productivity.

 

Modern Web Applications Development – MEAN and AngularJS

Standard

When we have to develop a web application we need to analyze the technology that we will use and we have to be sure that this technology will allow us to develop the project successfully. To develop the project successfully the technology should provide us some features, such as productivity, functionality, and scalability, among others.

Nowadays, JavaScript is a language that provides a wide range of possibilities, and there are many tools within the JavaScript environment that will help us to develop our projects successfully.

In this article I want to analyze what I think that is a very interesting stack for modern web application development and wherein AngularJS is the main player of any of the variants of the stack that I analyze.

 

Front End

Web Applications Desktop

As I mentioned previously, I think that nowadays AngularJS is one of the most interesting frameworks for developing the front-end of our web applications. Although AngularJS allows us to develop different types of applications, I think it is particularly interesting for the development of applications that need to implement CRUD actions, where access to databases is essential. Usually enterprise applications need to access data stored in our database, so I think that AngularJS is a framework to keep in mind when developing enterprise applications.

Mobile Applications

For the front-end there is another interesting framework that we must take into account, Ionic, which allows us developing hybrid mobile applications. Personally, I consider that one of the most important features of Ionic is that it is based on AngularJS, so we will be able to reuse most of our code developed for our web desktop application, achieving significant savings in development cost.

Furthermore, Ionic is based in PhoneGap, so we will be able to distribute our mobile application easily for the different mobile platforms available in the market.

 

Back End

We have some interesting options for developing our back-end, which we can group mainly in two different groups: cloud back-end and on-premises back-end.

 

Cloud back-end

There are some platforms that allow us define easily our data model in their servers and access them through an specific SDK or through an API REST.

There are two platform that I consider very interesting, Parse and Firebase, which you can try for free indefinitely, although with limited resources. Both platforms include SDKs for iOS, Android and JavaScript, among others.

Firebase also includes an specific SDK for AngularJS, and natively provide us developing realtime applications. So, we can define some events and when someone add, update or remove data from or to our collections then Firebase will notify in realtime to our clients.

If we finally decide to have our back-end on the cloud, when we develop our projects we are going to mainly focus on developing the front-end, because for the back-end we will have only to define our data model and we won’t have to develop anything.

 

On-premises Back-end

If we decide to have our back-end on our own servers then we have some frameworks that will help us developing our own back-end.

There are some frameworks that I would like to highlight although, at the end, is the development team who will choose one or other depending on their preferences: SailsJS, Synth, LoopBack, Restify, Deployd and MeanJS. Another choice is develop our own back-end manually, with NodeJS + Express, for example, or with another platform or programming language.

Most of these frameworks allow us define our API easily and very quickly so, once we have developed our API, we will have to focus on developing our front-end.

 

Conclusion

Developing web applications and mobile applications is quite complex, however, if we choose proper tools we could reduce the complexity and we could improve our productivity.

With this article I have tried to analyze an stack, with some variants, that I think is very interesting and that help us developing our web and mobile applications.

Nowadays I think that one of the most interesting frameworks for developing the front-end is Angularjs, and Ionic for developing the mobile app. For developing the back-end I would choose Firebase if it isn’t mandatory to store our data in our own servers, and I would choose SailsJS, LoopBack or MeanJS if we have to store our data in our servers.

In the following articles I will explain how to develop web and mobile apps with the tools analyzed in this article.

Realtime JavaScript Stack: nodejs + express + mongoose + socket.io + angularjs

Standard

There is a good realtime JavaScript stack, composed by nodejs + express + mongoose + socket.io + angularjs, and I’m going to explain how to integrate these pieces of software to develop a simple web application. The application that I have developed is called VoteExpress, and through this application users are able to vote the team that they think that will win the next Brazil World Cup 2014. When a user votes for a team, every users connected to the page will be notified in realtime that someone has voted that team, and a pie chart will be automatically updated with the new results.

Demo ApplicationSource Code

We can bootstrap our application with the following skeleton: https://github.com/jlmonteagudo/node-express-moongose-min-bootstrap  This skeleton is based on the excellent project developed by Madhusudhan Srinivasa project: Nodejs Express Mongoose Demo, that use best practices developing nodejs web applications.

This is the main tree folder of the skeleton project:

  • app
    • controllers
    • models
  • config
    • config.js
    • db-fixture.js
    • express.js
    • routes.js
    • socket-io.js
  • public
  • server.js

 

The Back End

The back end will manage RESTFUL requests, and these requests will be done by an AngularJS application on the front end, which will be located in the public folder.

The only entity that our application will manage is Team. To manage this entity we only have to create its Schema, its controller and its routes.

Inside the app/models folder we will create team.js, where we will define our model through Moongose (Mongoose Quick Start):

 

 

Next, we will create a controller in the folder app/controllers:

 

 

In the controller we define the actions that we will do with our models. list will return a JSON of all the teams with its scores, and update will update the score of the team and will notify about this to all the clients connected to the application.

Finally we have to define the routes in the file config/routes.js:

 

The Front End

The front end is an AngularJS application that is located in the public/js folder. Its tree folder is as follow:

  • controllers
    • team.js
  • directives
    • chart.js
  • services
    • socketio.js
  • app.js

In app.js we only define the routes:

 

 

In the controller we get all the teams that are inside the database, and we define the function vote that will be invoked when someone votes for a team. In the controller also is defined what to do when the server notify that a team has been updated. Here is the controller code:

 

 

We have defined a directive to render the chart (through Google Visualization API):

 

 

So, to render a chart inside a view we only have to insert the following code:

<chart></chart>

and that tag will render a Pie Chart through the Google Visualization API using the JSON document got from the server.

Finally, I have defined a service (services/socketio.js) that will be used to manage socket.io connections. The code is based on this article  http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets/

 

Conclusion

As we have seen, this is a simple stack that we can use to create our real time applications. In the JavaScript ecosystem there are another systems that allow us to develop this kind of applications, but I think that this one is very flexible.

There are many alternatives to the stack that I have proposed in this article, and two of them that I think that are very interesting are sails.js and Meteor. Maybe I will translate the VoteExpress demo developed in this article to sails and meteor, so we can compare its features.

 

Disclaimer

There are some things in the code that I don’t like and I think that there would be a better way to code. I would be happy if you could propose a better solution.

The first one is that I have defined the socketIO variable as global in the voteExpress/config/socket-io.js file. I know I could pass the socketIO paramater to config/routes and from here to each controller, but I didn’t like the solution.

The second one is related to Angular. I have used Pines Notify, to notify that someone has voted for a team, and I call to it as a JQuery method inside the controller: $.pnotify({title: ‘Vote’, text: ‘+1 vote for ‘ + team.name }); I know that it is a bad practice to update the DOM from the controller, and that it is much better to do that through a directive. Do you have any sugestion to solve this subject in a better way?