Building An E-Commerce Application With MEAN - Sample Chapter
Building An E-Commerce Application With MEAN - Sample Chapter
ee
This book will show you how to create your own e-commerce
application by taking you step by step through the parallel
processes of learning and building, using the MEAN stack.
You will also learn to develop a production-ready, high-quality
e-commerce site from scratch and gain the knowledge to
add your own features to the e-commerce site.
This book initially introduces the MEAN stack, which is
followed by a step-by-step approach to building a store
with AngularJS, setting up a database with MongoDB,
creating a REST API, and wiring up AngularJS. You will
learn to manage user authentication and authorization,
check multiple payment platforms, add product search and
navigation, deploy a production-ready e-commerce site,
and finally add your own high-quality feature to the site.
By the end of the book, you will be able to build and use your
own e-commerce app in the real world and will also be able
to add your own new features to it.
P U B L I S H I N G
Adrian Mejia
$ 34.99 US
22.99 UK
Building an E-Commerce
Application with MEAN
pl
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
Building an E-Commerce
Application with MEAN
Develop an end-to-end, real-time e-commerce application using
the MEAN stack
Sa
m
Adrian Mejia
Preface
E-commerce platforms are widely available these days. However, it is common to
invest a significant amount of time in learning to use a specific tool and realize later
that it does not fit your unique e-commerce needs. So, the greatest advantage of
building your own application with an agile framework is that you can quickly meet
your immediate and future needs with a system that you fully understand.
The MEAN stack (MongoDB, ExpressJS, AngularJS, and NodeJS) is a killer JavaScript
full stack combination. It provides agile development without compromising on
performance and scalability. It is ideal to build responsive applications with a large
user base, such as e-commerce applications.
This book will teach you how to create your own e-commerce application using
the MEAN stack. It will take you step by step through the process of learning and
building parallelly. Using this guide, you will be able to show a product catalog,
add products to shopping carts, and perform checkouts. It will cover product
categorization, search, scalable deployment, server setups, and other features.
At the end of this book, you will have a complete e-commerce application that is
fully tested, scalable, and alive. Additional topics on how to scale the application,
server deployment, and security will also be discussed.
Preface
[1]
We are going to cover some ground in this first chapter, and then deepen our
knowledge on each of the MEAN stack components. The topics that will be
covered in this chapter are as follows:
Vibrant community. NPM packages have grown faster than any other
programming language community yet
Excellent for JSON APIs, Single- Page Applications (SPAs), and soft realtime applications
As for any other solution, there are some disadvantages as well, but they can be
mitigated as follows:
In general, this is how SPAs (and the MEAN stack) work: when a client request is
received from the user's browser, it hits the ExpressJS web server first. ExpressJS
runs on top of the NodeJS platform, and it connects to the MongoDB database as
needed. Finally, the client's request is answered with an AngularJS application. From
that point on, all subsequent requests are made behind the scenes through AJAX to
the ExpressJS API. AngularJS takes care of rendering any new data instantly and
avoiding unnecessary full-page refreshes.
[2]
Chapter 1
NodeJS
NodeJS is a platform that allows running of the JavaScript code outside of the
browser. It's built on top of Google Chrome's V8 JavaScript runtime environment.
Thanks to its non-blocking I/O and event-driven model, it is very fast and uses each
CPU cycle optimally.
The JavaScript event-loop is sometimes confusing for developers who are new to
JavaScript. In many popular languages (Java, Ruby, Python), each thread executes
only one line of code at a time (everything else is blocked). However, JavaScript was
conceived to be responsive at all times, so it makes heavy use of callbacks and the
event-loop. The event-loop is an internal loop that executes all the code, and does not
wait for anything in particular. The callbacks are called when a process is done. For
instance, for blocking the I/O, a database query will make the thread sit and wait for
the result. On the other hand, in JavaScript, it will continue executing the successive
lines of code. When the database result is ready, it will be handled by the callback.
Thus, non-blocking I/O.
NodeJS will be our server-side platform, and we will need it to run our web server,
ExpressJS.
[3]
ExpressJS
ExpressJS is a web framework for NodeJS. It is a very transparent webserver that
not only allows us to build web applications but also to expose RESTful JSON APIs.
Express is very modular, so we can process/modify any requests using something
called middleware. There are middlewares to provide authentication, handling
cookies, logging, error handling and other such functions.
MongoDB
MongoDB is an open source document-oriented database, one of the most popular
in the NoSQL database world. It favors a JSON-like document structure rather
than the more traditional table-based structures found in relational databases. Its
query language is very powerful and expressive. Later in this book, we are going to
compare the equivalent SQL queries to MongoDB queries.
MongoDB stores all the users' data, products, orders, and anything that needs to be
persistent in the e-commerce application.
AngularJS
AngularJS is an open source JavaScript MVC framework (it might also be referred
to as MV* or MVW[Whatever]). This framework enhances the HTML markups with
new directives, properties, and tags, and always keeps the views and models in sync.
AngularJS facilitates the creation of data-driven and Single-Page Applications (SPAs).
Installing NodeJS
The node community has been very busy lately and has created more packages for
it than any other existing platform. Not just packages but the core development too
has been forked (for example, ioJS) and merged back to the main line. Since we are
aiming for production, we are going with the current stable version v0.12. We are
going to use NVM (Node Version Manager) to switch easily between versions when
newer versions become stable.
[4]
Chapter 1
If you are a Windows user, you can see the instruction on the NVM site
at https://github.com/creationix/nvm.
The NodeJS installation comes with the NPM (Node Package Manager). You can
verify if node and npm were installed correctly by checking the versions, as follows:
$ node -v
# v0.12.7
$ npm -v
# 2.11.3
Installing ExpressJS
You can download Express using npm by typing the following in your terminal:
npm install -g [email protected]
Note that we are downloading a specific version using @4.13.3; the -g argument
means that we are installing the package globally.
[5]
Installing MongoDB
If you are using a Mac, I'd recommend installing brew first:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/
master/install)"
Ubuntu:
sudo apt-get -y install mongodb=3.0.2
For other operating systems, follow the instructions given at the official
site at https://www.mongodb.org/downloads.
[6]
Chapter 1
You will see a lot of things going on when you run the commands.
But don't worry, we are going to explain all the magic in the next few
chapters. For now, play along and get everything installed.
The command line has some kind of wizard that asks you about your preferences.
The following are the ones that we are going to use throughout the examples in
this book:
# Client
# Server
? What would you like to use for data modeling? Mongoose (MongoDB)
? Would you scaffold out an authentication boilerplate? Yes
? Would you like to include additional oAuth strategies? Google,
Facebook, Twitter
? Would you like to use socket.io? Yes
# Project
? What would you like to write tests with? Mocha + Chai + Sinon
? What would you like to write Chai assertions with? Expect
[7]
It takes a while, because it installs a number of packages for you. Take a look into
package.json and bower.json. Bower is another package manager like npm but for
the frontend libraries. After the installation is complete, you can run the example app
with these commands:
# Build
$ grunt
Example of the output of Batarang AngularJS extension for Chrome's web inspector.
Chapter 1
The server directory contains the NodeJS files, which handle ExpressJS
and MongoDB
app
assets
e2e
server
api
auth
- Authentication handlers
- App configuration
environment
views
Zooming into clients/app, we will find that each folder has the name of the
component (main page, products page), and that inside each folder are all the files
related to that component. For instance, if we look inside main, we will find the
AngularJS files, CSS (scss), and HTML:
meanshop/client/app/main
main.js
- Routes
main.controller.js
- Controller
main.controller.spec.js - Test
main.html
- View
main.scss
- Styles
Similarly, for our back-end, we have folders named after the components with all the
related files inside. We will find NodeJS files, ExpressJS routes, SocketIO events, and
mocha tests:
meanshop/server/api/thing
index.js
- Routes
thing.controller.js
- Controller
thing.model.js
- Database model
thing.socket.js
- Socket events
thing.spec.js
- Test
Components
There are a number of tools used in this project that you might be already familiar
with. If that's not the case, read the brief description given, and when needed. we
will describe it more thoroughly.
Testing
AngularJS comes with a default test runner called Karma, and we are going to
leverage its default choices:
Jasmine: This is the BDD framework for testing the JavaScript code, which is
executed with Karma.
Protractor: This is used for end-to-end tests with AngularJS. This is the
highest level of testing, which runs in the browser and simulates user
interactions with the app.
[ 10 ]
Chapter 1
Tools
The following are some tools/libraries that we are going to use for increasing our
productivity:
Yeoman (yo): This is a CLI tool for scaffolding web projects. It automates
the creation of directories and files through generators, and also provides
command lines for common tasks.
Travis CI: This is a Continuous Integration (CI) tool that runs your tests
suite every time you commit to the repository.
AngularJS full-stack: This is the generator for Yeoman that will provide
useful command lines to quickly generate server/client code and deploy to
Heroku or OpenShift.
BabelJS: This is the js-tojs compiler that allows the use of features from
the next generation JavaScript (ECMAScript 6) instantly, without waiting for
browser support.
Package managers
AngularJS comes with package managers for third-party backend and frontend
modules:
Bower: This is the frontend package manager that can be used to handle
versions and dependencies of the libraries and assets used in a web project.
The file bower.json contains the packages and versions to install, and the
file .bowerrc contains the path for the location where those packages need
to be installed. The default directory is ./bower_components.
[ 11 ]
Bower packages
If you have followed the exact steps for scaffolding our app, you will have the
following frontend components installed:
angular
angular-cookies
angular-mocks
angular-resource
angular-sanitize
angular-scenario
angular-ui-router
angular-socket-io
angular-bootstrap
bootstrap
es5-shim
font-awesome
json3
jquery
lodash
In the next chapter, we will dive deeper into AngularJS and our file structure. The
second part of this chapter is about the functionality of our final app.
Homepage
Marketplace
Backoffice
[ 12 ]
Chapter 1
Homepage
The homepage will contain the featured products, navigation, menus, and some
basic information, as you can see in the following image:
[ 13 ]
Marketplace
This section will show all the products, categories, and search results:
[ 14 ]
Chapter 1
Backoffice
You need to be a registered user for accessing the back office section.
[ 15 ]
After you log in, the app will present you with different options depending on your
role. If you are the seller, you can create new products, as shown in the following
image:
If you are an admin, you can do everything that a seller does (create products), and
you can manage all the users and delete/edit products.
[ 16 ]
Chapter 1
Add products with their title, price, description, photo, and quantity
[ 17 ]
The following are the features, captured as user stories, that we are planning to
develop through this book:
As a user, I want to see all the published products and their details when I
click on them.
As a user, I want to search for a product so that I can find what I'm looking
for quickly.
As a user, I want to check out products as a guest user so that I can quickly
purchase an item without registering.
As an admin, I want to manage user roles so that I can create new admins,
sellers, and remove seller permissions.
As an admin, I want to manage all the products so that I can ban them if they
are not appropriate.
All these stories might seem verbose, but they are useful for capturing the
requirements in a consistent way. They are also handy for developing test cases.
Learn more about user stories at https://en.wikipedia.org/
wiki/User_story.
[ 18 ]
Chapter 1
Summary
In this chapter, we discussed the reasons for using the MEAN stack to build our
e-commerce application, and got it installed. This is not just some kind of trend
which some companies are migrating to. It gives a tremendous performance boost
to the apps, and eases the learning curve using one main language for both, the
frontend and the backend. We also described the file structure that we are going to
use for organizing the code. Finally, we explored the features that the final app will
have, and the way it's going to look and behave. In the next series of chapters, we are
going to work with each piece of the MEAN stack individually. Later, we will start
integrating all the components and make them work together. The next chapter will
cover the most visible part: building the marketplace with AngularJS.
[ 19 ]
www.PacktPub.com
Stay Connected: