Building an E-commerce website in MEAN stack

Preview:

Citation preview

Building an eCommerce site in MEAN Stack

People10 Technosoft Private Limited

Agenda1) Javascript - An Introduction

2) The components of MEAN Stack

3) MEAN Stack - More about the components

a) Node.Js

b) AngularJs

c) MongoDB

4) Setting up the environment for MEAN Stack Coding

5) Building an eCommerce application - Preview

6) Q & A

2

Javascript - An Introduction

JavascriptJavascript is a High Level, Untyped and Interpreted programming Language.

Standardized in the ECMAScript language specification

Developed in 10 days in May 1995 by Brendan Eich, while he was working for Netscape

4

Let’s go back in TimeThe Year is 1995

5

Beginning

In 1995, Netscape hires Brendan Eich to create a programming Language for browser.

Netscape collaborates with Sun to include Java Applets - Little programs that could be run in the browser

Brendon is assigned with Task of creating a Glue Language to for the browser to allow to run Java Applets

6

Why Javascript is the way it is

Brendon opted for simplicity since because he thought that in all probability it was web designers who will be using it.

● Loosely typed interpreted language● Avoided niceties like compilers and formal OO System concepts● Made language forgiving of minor mistakes a more formal language would signal as errors and refuse to

run

7

Release historyECMAScript 3 released in 1999

ECMAScript 5 released in 2009

ECMAScript 6 released in 2015

On yearly release schedule as of now

8

Features

Imperative Style

Borrows Structured programming Style from C

Dynamically Typed

Prototype Based

Functions are First Class Citizens

9

Meteoric Rise of JSRise of AJAX, Rich UI Apps

Monopoly in Browser space / Web

Adoption of Internet, Network speeds are on the rise.

List of languages that compile to JS (Over 250)

https://github.com/jashkenas/coffeescript/wiki/list-of-languages-that-compile-to-js

10

The components of MEAN Stack

JSON

JSON

JSON

JSON

Collection of JavaScript based technologies used to develop web applications.

BSON

12

MEAN Stack - More about the components

Node.jsBe Curious

Ryan Dahl

IntroductionNode.js is a complete software platform for scalable server-side

and networking applications

Node.js is an Evented Non blocking I/o Server side language.

Node establishes real-time, two-way connections!

Built on the Google V8 JavaScript engine

HistoryDeveloped by Ryan Dahl in 2008

Showcased first at JS Conf in Europe in 2009.

In 2010 Joyent sponsors Node.js development.

Dahl stepped aside, promoting co worker and npm creator Isaac Schlueter to

manage the project

History io.js, a fork of Node.js created in 2014, Due to internal conflict over Joyent's

governance

2015 - Jun, the Node.js and io.js communities voted to work together under the

Node.js Foundation

2015 - Sep, Node.js v0.12 and io.js v3.3 were merged back together into Node

v4.0

ComponentsMain core, written in C and C++

Modules, such as Libuv library and V8 runtime engine, also written

in C++

Overall StructureAll requests handled by the Main Single Thread

API in JavaScript

Libuv responsible for both asynchronous I/O & event loop

Libuv contains fixed-size thread pool

Architecture

NpmIn 2011, a package manager was introduced for the Node.js

environment called npm. The package manager makes it easier for

programmers to publish and share source code of Node.js libraries

and is designed to simplify installation, updating and uninstallation

of libraries

AdvantagesPlays very well with real time applications

Vibrant Community

Tons of Modules

Unified JavaScript development stack

Node.js can be combined with a browser, a document database

(such as MongoDB or CouchDB) and JSON

Why Should you Invest in JS

It’s HOT.

HOT ENOUGH TO SEAL A JOB FOR A FAILED BROKE ENTREPRENEUR

WITHIN 48 HRS.

FLAT

24

25

26

Why Should you Invest in JSExcellent gateway for Entrepreneurs

Web has become Ubiquitous, So has the monopoly of JS

Hybrid Mobile Apps - Iconic, PhoneGap

Rise of Node.js (Unified Stack)

It is Evolving and is under a yearly release schedule

27

AngularJS

➔ AngularJS is a Client side Javascript framework developed and maintained by

Google. It is not a Javascript library like jQuery.

➔ Allows developing well architectured and easily maintainable web-applications.

➔ Simply an extension to HTML with new attributes.

➔ Has its own implementation of jQuery for DOM manipulation called jqLite. No

need to include jQuery.

➔ AngularJS makes use of declarative programming for building UI.

➔ Write code in such a way that it describes what you want to do, and not how you

want to do it. It is left up to the compiler to figure out the how.

➔ Write less do more.

AngularJS

29

Key features of AngularJS● MVC Architecture

30

Key features of AngularJS● Two way data binding

31

Key features of AngularJS● Modules

32

Key features of AngularJS● Dependency Injection

33

Key features of AngularJS● Directives

34

Example:

<only-number></only-number>

<input type=”text” ng-model=”time” only-number/>

Key features of AngularJS● In built Templating

● Excellent support for developing single page applications

● End to End Integration Testing / Unit Testing

Huge Community. Highest github stars (35,311) among client side JS frameworks.

35

How does Angular compiler work?

HTML:

36

JS:

var myApp = angular.module(“testApp”,[‘ui.router’]);

myApp.controller(“customerCtrl”,function($scope, $http){

$scope.Customer = {};

$scope.submitData = function(){

$http.post(baseUrl+’/cust’,$scope.Customer);

}

});

Angular compiler traverses the DOM looking for attributes, finds attributes that are specific to angular. These

special attributes are basically Directive functions that will be called.

<html><body ng-app=”testApp”> <form ng-controller=”customerCtrl”> <input type=”text” id=”fname” ng-model=”Customer.fName”/> <input type=”text” id=”lname” ng-model=”Customer.lName”/> <button ng-click=”submitData”>Submit</button> </form></body></html>

MongoDB

The NoSQL Movement

As stated in nosql-database.org, the definition of NoSQL is

Next Generation Databases mostly addressing some of the points: being non-relational, distributed, open-source and

horizontally scalable.

It’s all about using the right choice. Not SQL is the only best option.

Consider all options and choose wisely.

★ Non Relational

★ Distributed

★ Open-Source

★ Horizontally Scalable

★ Schema-less or dynamic schema

★ Replication Support

38

Not Only SQL

Why NoSQL for eCommerce➔ The data dilemma nature of eCommerce.

➔ Sane Schema - Which usually fits to one vertical

◆ Fine with few types of products

◆ Becomes tough when the types of products grow

➔ Insane Schema - Which is flexible

39

Why NoSQL for eCommerce - Contd.,We are building an online shopping site, and we start with selling books in online.

A sample product information schema would be

Product

id:

sku:

price:

description:

…….

author:

title:

publisher:

isbn:

pages:

language:

Book Schema

40

Why NoSQL for eCommerce - Contd., And, we plan to extend our site to sell music albums

Book Schema Album Schema

Product

id:

sku:

price:

description:

…….

author:

title:

publisher:

isbn:

pages:

language:

Product

id:

sku:

price:

description:

…….

artist:

title:

release_date:

Format: CD/DVD

language:

41

Why NoSQL for eCommerce - Contd., And, now we plan to extend our site to dresses, probably we start with some branded jeans

Book Schema Album Schema Jeans Schema

Product

id:

sku:

price:

description:

…….

author:

title:

publisher:

isbn:

pages:

language:

Product

id:

sku:

price:

description:

…….

artist:

title:

release_date:

Format: CD/DVD

language:

Product

id:

sku:

price:

description:

…….

brand:

gender:

make:

style:

color:

material:

Length:

width:

42

How do we generally address such requirements in a RDBMS?

1) Add all the attributes in the same table.

2) Create different tables for each type of products.

3) Create a master table with common attributes, and make

individual tables for each type of products.

Major issues faced in such approaches

1) Horizontal scalability of the products table

2) Slow and inefficient search queries

Why NoSQL for eCommerce - Contd.,

43

How can we address this in MongoDB?

Products Collection

{ id: “10000”, “sku” : 50, “price” : 1500, “description” : “”, “title” : “MongoDB Definitive Guide”, “author” : “Kristina Chodorow”,

“publisher” : “o-reilly”}

{ id: “10001”, “sku” : 250, “price” : 750, “description” : “The best album of the year”, “title” : “Black Star”, “artist” : “David Bowle”,

“format” : “DVD”, “language” : “english”}

{ id: “10002”, “sku” : 500, “price” : 2000, “description” : “The slim fit jeans”, “brand” : “London Jeans”, “color” : “Dark Blue”, “material” :

“cotton” }

Why NoSQL for eCommerce - Contd.,

44

MongoDB➔ MongoDB - the name derived from ‘humongous’ (huge).

➔ Is a free, open-source, cross-platform, high-performance, scalable, and document

based database.

➔ Is also a NoSQL (Not Only SQL) database.

➔ First released on 2009 by a company named 10gen, and later in the year 2013

10gen converted to MongoDB Inc, and the latest version now is 3.2.

➔ MongoDB is written in c++

➔ The philosophy behind NOSQL / MongoDB

◆ Stored in a format other than tabular format, usually in key-value pairs.

◆ Non relational databases scale horizontally much easily than relational

◆ Not concerned with the transactional stuff.

45

MongoDB➔ Mapping SQL Knowledge with MongoDB

SQL MongoDB

Database Database

Table Collection

Row Document

Column Field

Joins Embedded Documents

Primary Key Primary Key

46

MongoDB - Contd., (Key Features)◆ Document

● At the heart of the MongoDB

● An ordered set of keys with associated values

◆ General purpose database / Stores data in JSON format

● { “field1”: “value1”, “field2”: “value2”}

● {“first_name” : “William”, “last_name” : “Shakespeare”}

◆ Embedded documents

● We can chose to embed related data in one document.

● With one query we can completely retrieve the information we need

{“first_name” : “William”, “last_name” : “Shakespeare”, “phone”: [ {“type” : “home”,

“number” : “+552133332343”} , {“type” : “work” , “number”: “+552100002356”} ] }

47

MongoDB - Contd., (Key Features)➔ Key Features

◆ Dynamic Schema

● {“first_name” : “William”, “last_name” : “Shakespeare”}

● {“first_name” : “George”, “middle_name” : “M”, “last_name” : “Eliot”}

◆ Effective Querying

● Perform ad-hoc queries on the db using find, findOne functions

● We can query for ranges of records, in-equalities and other operations by using $-

conditionals. $-conditionals are in-built functions in MongoDB

● Retrieving the details of all the customers in a database, is as simple as executing the

following command db.Customers.find() in the terminal.

● We have Comparison, Logical, Evaluation and Array operators for effective querying.

48

MongoDB - Contd., (Key Features)◆ Indexing

● A database index is similar to book’s index.

● A query that does not use an index is called a table scan.

● We can create indexes of fields, or fields of embedded documents.

● E.g db.Customers.createIndex ({username : 1}) (creates an index in the username field in the

ascending order)

● Indexes use a B-Tree data structure at the implementation level.

● Can be created on a single field, or more than one field.

● E.g db.Customers.createIndex ( {“state” : 1, “zipcode” : 1})

◆ Sharding

● Is the technique of distributing data through multiple physical partitions called shards

● Even though the db is physically partitioned, to the users the database is a single instance.

49

MongoDB - Contd., (Key Features)◆ Automatic Failover

● Is a resource, that allows automatically to switch data handling to a standby system in the

event of system crash.

● MongoDB achieves this via Replica set.

● In a replica set, the primary member is the current master instance, which receives all write

operations, and a secondary member always replicate the contents of the primary member.

● Secondary might handle read requests, but only the primary members can handle the write

operations.

● The failover process in MongoDB makes the secondary to become the primary replica set in

case of failovers.

50

MongoDB - Contd. - Sharding

51

MongoDB - Contd. - Automatic Failover

52

Setting up the environment before getting MEAN

Installing on Unix OS:

$ sudo apt-get update

$ sudo apt-get install git

Installing on Windows:

● Visit the below link https://git-scm.

com/download

● Select windows as the OS,

Download should immediately

start after you are redirected.

Git is a free and open source distributed version control system designed to handle

everything from small to very large projects with speed and efficiency.

54

Installing on Unix OS:

Import public key of MongoDB apt repository using the following command

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927

Add MongoDB APT repository url in /etc/apt/sources.list.d/mongodb.list

$ echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb.list

After adding required APT repositories, use following commands to install MongoDB

$ sudo apt-get update$ sudo apt-get install mongodb-org

55

Installing on Unix OS - Continued. :

After installation MongoDB will start automatically. To explicitly start/stop the service use the following

commands

$ sudo service mongod start$ sudo service mongod stop

Verify MongoDB installation by starting the mongo shell using the following command

$ mongo

> use mydb;

> db.test.save( { tecadmin: 100 } )

> db.test.find()

{ "_id" : ObjectId("52b0dc8285f8a8071cbb5daf"), "tecadmin" : 100 }

56

Installing on Windows :

● Download MongoDB from official MongoDB website (https://www.mongodb.com).

● Extract the files to your preferred location, for example d:\mongodb\

● Create a MongoDB config file, it’s just a text file.

for example d:\mongodb\mongo.config

##store data heredbpath=D:\mongodb\data

##all output go herelogpath=D:\mongodb\log\mongo.log

● Use mongod.exe --config d:\mongodb\mongo.config to start MongoDB server

d:\mongodb\bin>mongod --config D:\mongodb\mongo.configall output going to: D:\mongodb\log\mongo.log

57

Installing on Windows - Continued :

● Use mongo.exe to connect to the started MongoDB server

d:\mongodb\bin>mongoMongoDB shell version: 2.2.3connecting to: test> //mongodb shell

● Install as Windows Service with --install

d:\mongodb\bin> mongod --config D:\mongodb\mongo.config --install

58

Installing on Unix OS:

$ sudo apt-get update

$ sudo apt-get install nodejs

$ sudo ln -s /usr/bin/nodejs

/usr/bin/node

$ sudo apt-get install npm

Installing on Windows:

● Download the windows installer

from https://nodejs.org/en/

● Run the installer (the .msi file you

downloaded in the previous step.)

● Follow the prompts in the installer

● The installer package also comes

with npm, make sure to select npm

option while installing.

59

● Bower is a package manager optimised for front-end. It is a command line utility.

● Bower requires node, npm and git.

● Install it with npm

$ npm install -g bower

● Install packages with bower install● Bower installs packages to bower_components/ folder in your project root by

default.

● Create a bower.json file for your package with bower init

● Then save new dependencies to your bower.json with --save option.

$ bower install <PACKAGE> --save

● Use packages through bower_components/

<script src="bower_components/jquery/dist/jquery.min.js"></script>

60

● Create a directory to hold your application, and make that your working directory

$ mkdir myapp

$ cd myapp

● Use the npm init command to create a package.json file for your application

$ npm init

● Above command will prompt you for a number of things. Hit Return to accept the

default values.

● Install Express in the app directory and save it in the dependencies list

$ npm install express --save

61

Building an eCommerce App - PreviewThe MVP for an eCommerce site

➔ A marketplace, where users can

➔ Search for products

➔ Add products to shopping cart

➔ Check-out

➔ View their order summary

➔ An Admin Panel

◆ Where admin can add/update products / categories

◆ Where admin can view the orders placed

62

Building an eCommerce App - PreviewOur Demo

➔ Designing the data model in MongoDB

➔ Building the database in MongoDB

➔ Setting up an express app, and the overview of the project structure.

➔ Creating RESTful APIs with NodeJs & Express Js

➔ Building the storefront in AngularJs and integrating the front-end app with

the NodeJs API

➔ Hosting the app live in Heroku, MongoLab

63