Rockstar Developer by Ei - Maung
Rockstar Developer by Ei - Maung
Rockstar Developer by Ei - Maung
Fairway Web
10x Programmer
[ rsdbook.com ]
Copyright 2016, Ei Maung, Fairway Technology.
License - CC-BY-NC-SA
This document is free to share, copy, distribute and transmit. And, also allow to remix or
adapt to this document. But, you must attribute the work in the manner specified by the
author or licensor (but not in any way that suggests that they endorse you or your use of
the work). And, you may not use this work for commercial purposes. If you alter,
transform, or build upon this work, you may distribute the resulting work only under the
same or similar license to this one.
For any reuse or distribution, you must make clear to others the license terms of this work.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
() Key Concepts
() Development Processes Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
() Test Driven Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
() SOLID Design Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
() Service Oriented Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
() Project Management
() Version Control System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
() Issue Tracking System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
() Team Collaboration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
() Development Wrokflow Automation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rockstar Developer 3
Programming
()
Program-
ming MCC
Programming Low Level Programming
Low Level
Low Level
High Level
()
Software Development Language BASIC, Pascal ,
COBOL, C, C+, VB, Standalone, Client-Server, Three-Tier, Web
Sun Microsystem John Gage () "Network is the computer"
Cloud Computing Mobile Internet
of Things
Monitor Keyboard, Mouse CPU
Software Development
Software Development
Background Theory
Managing Director (Enterprise Solutions)
Vice President 2 (MCPA)
Rockstar Developer 4
Rockstar Developer
Rockstar
Software Developer
Rockstar
(Theory) (Tools)
Developer
()
Software Development
Rockstar Developer
Professional Web Developer Web Standards, jQuery, HTML5
PHP, MySQL, MVC, Web Application Security Web Developer
Ubuntu Linux
Web Developer Software Developer Linux Operating System
Ubuntu
Code
Project Management
NodeJS, MongoDB Software Development Server Architecture
Web Development
Business Solution, Web App, Mobile App, Game Software
Software Web Technology
Software
Web Technology Backend
Web Developer
Mobile App Developer Business Solution Developer Software Engineer
10x Programmer
Programmer
Programmer
Rockstar Developer 9
Any fool can write code that a computer can understand. Good programmers
write code that humans can understand. Martin Fowler
Programmer Programmer
Code Code
Programmer
( )
Bus Factor
Software Project Bus Factor
Software Project
Programmer
Code Programmer
Code Maintain
Programmer Programmer
Rockstar Developer 10
Code
Programmer Code
Code Code
Code Programmer
Code by coincidence
Code
Code
Accidents of implementation
Programmer
Programmer
Code
Bug
" Project
"
Code Code
Rockstar Developer 11
Bug
Project Bug Fix
Code
Code
Code Language
Process
Management, Source Code Management, Design Principles Design Architecture Software
Engineering
10x
Programmer Code
Scalable 10x
Programmer Rockstar Developer
10x Programmer
Rockstar Developer
()
Key Concepts
Software Project
"...
"
"
"
" "
"
"
"
"
"
"
"
"
"
"
"
"
Rockstar Developer () Development Processes Management 15
"
"
Software Developer
Software
Source projectcartoon.com
Solution
Sense
Software Customer
User Feedback
Rockstar Developer
Software
User Feedback Development Process
Software Product
Software
Test Driven Development (TDD) Coding
Unit Level, Function Level Test
Business Model
Business Model Canvas (.)
Data Collection
Data
Data Structure Model
Software
Test Method Unit Testing
Unit Function
Integration Testing
Unit
Specification System Testing
Acceptance Testing Software Development Process
Rockstar Developer () Development Processes Management 19
Software Product
Software
Business Model Requirements
Source Code Management System Build
Automation Virtualization Source Code
Management System () Build Automation ()
Virtualization Docker ()
Software Solution
Server
Production Environment
Setup Load Balancer Setup
Database Replication Server Architecture
() Common Server Architectures
Source Wikipedia
Junior Developer Team
Lead Developer Project Manager
Requirements Specification System Design Junior Developer
Spec Design Coding
Specification
User Specification
Software Product
Requirements Specification
System Design
Coding
Rockstar Developer () Development Processes Management 21
Product
Specification System Design
Waterfall Model
Requirement Specification
Specification
Product Innovative
Product - Product
Product Specification
User Product
Domain Knowledge
Product Vision Software
Specification Waterfall Model
1. Adaptive Planning
Plan
2. Evolutionary Development Product
Rockstar Developer () Development Processes Management 22
Agile Development
(Principle)
Processes Management
Agile Development () Agile Method () Agile Process Management
Architecture
Product
Prototype Coding User
Feedback Specification Code Software
Development Process Software Product
Feature
Construction
Rockstar Developer () Development Processes Management 23
Feature Feature
User Feedback
Transition
Iterative Development Product
Feature Incremental Development
Source Wikipedia
Iterative Development
Product Waterfall Model Risk
Iterative Development
SCRUM
Project Management () Team Collaboration
Conclusion
Development Process Management
Waterfall Model Planning
Requirement Analysis System Design
Iterative Development Planning
Development Plan
Source: Wikipedia
Iterative Development
Iterative Development Agile Method Waterfall
http://eimaung.com/courses
Rockstar Developer () Test Driven Development 27
Project Presentation ()
Customer
Key Point
Delivery Route
Mobile App Delivery Route Maps
... Map
Perfect Size
Font-Size: 9pt Font-Size: 11pt
Impression Out
...
"
Order
Delivery Rout "
" "
Rockstar Developer () Test Driven Development 28
""
"
"
"
"
"... "
""
" ...
"
Decoupling
Function () Component
Function
Function Function
Function
Function Function Function
Project Code
Technical Debt
Code Test Method
Rockstar Developer () Test Driven Development 30
Regression Test
-
Acceptance Test
- Warning Message
Function
Function Function JavaScript
Code
Pseudo-code
1. function getTemp() {
2. return getTempFromServer("/path/to/api");
3. }
4.
5. function testTemp() {
6. var temp = getTemp();
7. if(temp.degc > 32) print("Warning: High Temperature");
8. }
getTemp() Function
testTemp()
Function Temperature 32 Degree
Warning Message testTemp() Function Evaluate
getTemp() Function
testTemp() Function
Debug Log
Rockstar Developer () Test Driven Development 32
Pseudo-code
5. function testTemp() {
6. var temp = getTemp();
7. console.log("Temprature: " + temp.degc);
8. if(temp.degc > 32) print("Warning: High Temperature");
9. }
Pseudo-code
1. function getTempStub() {
2. console.log("Working with stub: getTemp()");
3. return {
4. degc: 24,
5. degf: 45
6. }
7. }
8.
9. function getTempMock(degc) {
10. console.log("Working with mock: getTemp()");
11. return {
12. degc: degc,
13. degf: Math.round((degc * (5/9) + 32))
14. }
15. }
16.
17. function getTemp() {
18. return getTempFromServer("/path/to/api");
19. }
getTempMock() Function
getTemp() Function
getTempStub()
Degree
Celsius getTemp() Function Object Object
Degree Celsius Return Value
getTempStub() getTemp()
Function
getTempMock() Function getTemp() Function
Stub Mock Function Model
Stub Mock
Remote Data Source Remote Data Source
Server Request
Function Database
Function GPS Fingerprint External
Input Device
JavaScript
Function
now time
Test
Function
Rockstar Developer () Test Driven Development 35
JavaScript
prettyDate() Function
JavaScript
Rockstar Developer () Test Driven Development 36
JavaScript
Test Result
Result Formatter
http://code.jquery.com/qunit/qunit-1.15.0.js
http://code.jquery.com/qunit/qunit-1.15.0.css
HTML
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="utf-8">
5. <title>QUnit Test</title>
6. <link rel="stylesheet" href="css/qunit.css">
7. </head>
8. <body>
9. <div id="qunit"></div>
10.
11. <script src="js/qunit.js"></script>
12. <script src="js/app.js"></script>
13. <script src="js/tests.js"></script>
14. </body>
15. </html>
notDeepEqual() Function
ok() true true
Test Pass
Test Fail equal() notEqual() Function
deepEqual()
notDeepEqual() equal(), notEqual()
Object deepEqual() notDeepEqual()
Function Test Code
QUnit tests.js
JavaScript
Fail Fail
2 day ago
2 days ago
Test () ()
Test Fail
expect() Function
JavaScript
() () Test Fail
JavaScript
Test -
Database Record Function
Pseudo-code
QUnit qunitjs.com
JavaScript
JavaScript
1. function sortByDistance(list) {
2. var result = [];
3. for(x in list){
4. result.push([x, list[x]])
5. }
6. result.sort(function(a,b){ return a[1] - b[1] });
7. return result.reverse();
8. }
Test Fail Code Quality
Test Code
Code Maintainability
Function
Test Code Run
Function
Test Function
Function
Test Refactoring
Code Refactoring
Code
Rockstar Developer () Test Driven Development 44
TDD Approach
Developer Code
Project
Conclusion
Ruby on Rails
Web Application Framework David Heinemeier
Hansson () "TDD is dead. Long live testing."
Developer Ruby on
Rails TDD Framework TDD
Developer
DHH
Programmer
Unit Test
Maintainable Quality Code
Test Driven Approach Quality Code
TDD Code
Developer
http://eimaung.com/courses
Rockstar Developer () SOLID Design Principles 46
Object-oriented Programming ()
1. Object
2. Information Hiding
3. Inheritance
4. Interface
5. Polymorphism
Object
Object
Data
Function
Object
Object
Object
Function
Data Function Object
Type Subtype Object Type Subtype Object Hierarchy
Code
Pseudo-Code
Rockstar Developer () SOLID Design Principles 48
Class
Pseudo-code
1. class Square
2. {
3. var width = 5;
4. var height = 5;
5.
6. function setSize(size) {
7. width = size;
8. height = size;
9. }
10.
11. function getArea() {
12. return width * height;
13. }
14. }
Pseudo-code
Pseudo-code
1. class Square
2. {
3. var width;
4. var height;
5.
6. function Square(size) {
7. width = size;
8. height = size;
9. }
10.
11. function setSize(size) {
12. width = size;
13. height = size;
14. }
15.
16. function getArea() {
17. return width * height;
18. }
19. }
Pseudo-code
Object-oriented Programming
Information Hiding
Object Data Function Data Function
Object -
Object
Object
Inlet Valve Outlet
Rockstar Developer () SOLID Design Principles 50
Valve / Piston
Object Object Data Function
Data Function Object
Information Hiding Information hiding Encapsulation
Information Hiding
Language Public, Private, Protected, Static
Access Control Modifier Language Access Control
Pseudo-code
1. class Engine
2. {
3. public var kilo;
4. private var pistons = 4;
5. private var valves = 12;
6.
7. public function dirve() {
8. kilo++;
9. }
10.
11. public function check() {
12. if( dirtyOil() )
13. print "Please change engine oil!";
14. }
15.
16. private function dirtyOil() {
17. if(kilo > 3000) return true;
18. return false;
19. }
10. }
Pseudo-code
Pseudo-code
1. class Math
2. {
3. static var PI = 3.1416;
4. static function round(value) {
5. return parseInt(value);
6. }
7. }
Pseudo-code
1. print Math.PI;
2. print Math.round(4.2);
Inheritance
Inheritance
Object Class Object Class Data
Function Inheritance
Object
Object
Hierarchy
Object Object
Inherit Object Data Function
Object Object
Object Object Data Function
Pseudo-code
1. class Animal
2. {
3. var legs = 4;
4.
5. function eat() {
6. ...
7. }
8. }
9.
10. class Bird extends Animal
11. {
12. var legs = 2;
13. var wings = true;
14. }
15.
16. class Dog extends Animal
17. {
18. function bark() {
19. ...
20. }
21. }
Rockstar Developer () SOLID Design Principles 54
(.)
Object
Multiple Inheritance
Pseudo-code
1. class Animal
2. {
3. function giveBirth() {
4. ...
5. }
6. }
7.
8. class Bird extends Animal
9. {
10. var legs = 2;
11. var wings = true;
12. function giveBirth() {
13. layEggs();
14. }
15. }
16.
17. class Horse extends Animal
18. {
19. var legs = 4;
20. function giveBirth() {
21. birthLive();
22. }
23. }
24.
25. class FlyingHorse extends Bird, Horse
26. {
27. ...
28. }
29.
30. var pegasus = new FlyingHorse();
31. pegasus.giveBirth();
giveBirth() Function
FlyingHorse Class Bird Horse Inherit
() FlyingHorse Class Object pegasus giveBirth()
Bird Horse Class
giveBirth() Function Bird giveBirth()
Horse giveBirth()
Deadly diamond of death
Interface
Text Box, Password Box Email Box Input Box
Input Box Size
Property Input Box
Input Box Click Keyboard Input Box
Text Box Password Box
Star Text Box
Password Box Password Box Text Box
Interface
Object Text Box Password Box
Text Box
Object Password Box Object
Object Text Box Password Box
Code Design
Interface
Object
Rockstar Developer () SOLID Design Principles 56
Pseudo-code
1. interface InputBox
2. {
3. function setValue(val);
4. function showValue();
5. function resize(width, height);
6. }
7.
8. class TextBox implement InputBox
9. {
10. var value;
11. function setValue(val) {
12. value = val;
13. }
14. function showValue() {
15. print value;
16. }
17. function resize(width, height) {
18. ...
19. }
20. }
21.
22. class PasswordBox implement InputBox
23. {
24. var value;
25. function setValue(val) {
26. value = val;
27. }
28. function showValue() {
29. for(var i=0; i < value.length; i++) {
30. print "*";
31. }
32. }
33. function resize(width, height) {
34. ...
35. }
46. }
TextBox PasswordBox
Class Input Box Interface Class
setValue(), showValue() resize()
Function
Polymorphism
Polymorphism
Object Function
Static Polymorphism Dynamic Polymorphism Static
Polymorphism
Function Overload Dynamic
Polymorphism
Inheritance Interface
Pseudo-code
1. class Shape
2. {
3. function area(r) {
4. return 3.14 * r * r;
5. }
6.
7. function area(x, y) {
8. return x * y;
9. }
10.
11. function area(x, y, z) {
12. return x * y * z;
13. }
14. }
Pseudo-code
Function Signature
Static
Polymorphism Dynamic Polymorphism Interface
Pseudo-code
1. interface Animal
2. {
3. function move();
4. }
5.
6. class Dog implement Animal
7. {
8. function move() {
9. print "Dog walk and run";
10. }
11. }
12.
13. class Bird implement Animal
14. {
15. function move() {
16. print "Bird fly";
17. }
18. }
Pseudo-code
Polymorphism
Creating Objects
JavaScript Object JSON
JSON
Classical OOP Class Object
Constructor Object
JavaScript
1. function Person() {}
Person Function
Function Object
JavaScript
JavaScript
JavaScript
1. function Person(name) {
2. this.fullName = name;
3. this.sayName = function() {
4. console.log("Hello, I am " + this.fullName);
5. }
6. }
Rockstar Developer () SOLID Design Principles 61
JavaScript
Information Hiding
JavaScript Public, Private Access Control Modifier Information Hiding
Object Data
Function Constructor this Data
Function this Constructor
Private Data Function
JavaScript
1. function Person(name) {
2. this.fullName = name;
3. this.sayName = function() {
4. sayHello(this.fullName);
5. }
6.
7. function sayHello(name) {
8. console.log("Hello, I am " + name);
9. }
10. }
11.
12. var foo = new Person("James");
13. foo.sayName(); // => Hello, I am James
14. foo.sayHello(); // => TypeError: foo.sayHello is not a function
Inheritance
JavaScript Object Constructor Prototype Inheritance
JavaScript
JavaScript
1. function Person(name) {
2. this.fullName = name;
3. this.sayName = function() {
4. console.log("Hello, I am " + this.fullName);
5. };
6. }
7.
8. function Student(name, major) {
9. Person.call(this, name);
10.
11. this.major = major;
12. this.sayMajor = function() {
13. console.log("I learn " + this.major);
14. }
15. }
16.
17. foo = new Student("Jame", "Computer Sciences");
28. foo.sayName(); // => Hello, I am Jame
29. foo.sayMajor(); // => I learn Computer Sciences
() Person.call() JavaScript
Function Object Person Object Constructor
Object call() Function Person
Function Object
Build-in Method
Inheritance Polymorphism
Interface
JavaScript Interface
Interface
Object
Static Type Language Interface
Object JavaScript Dynamic Type
Language Object
JavaScript
1. function Student() {
2. this.sayHello = function() {
3. console.log("Hello, I'm a student");
4. }
5. }
6.
7. function Worker() {
8. this.sayHello = function() {
9. console.log("Hello, I'm a worker");
10. }
11. }
12.
13. function greet(person) {
14. person.sayHello();
15. }
16.
17. var alice = new Student();
18. var bob = new Worker();
19.
20. greet(alice); // => Hello, I'm a student
21. greet(bob); // => Hello, I'm a worker
greet() Function
Object Student Object
Worker Object Object Interface
Object sayHello() Function Data Function
Rockstar Developer () SOLID Design Principles 64
3.3 SOLID
SOLID Principles Principles
OOP
Code
SOLID Code Design
SOLID
Principle of OOD (Object Oriented Design)
Uncle Bob
Robert C.
Martin
Software
Pseudo-code
Student Constructor
Object name major Assign
signRollCall() rollCall
displayInfo() Function name major HTML Format
Single Responsibility Student Object
name major Format
Constructor
Pseudo-code
Format ViewFormat
Student
XMLFormat
Format
Student
Implement
Single Responsibility Principle
Code Design
Open/Close Principle
SOLID O Open/Closed Principle
Rockstar Developer () SOLID Design Principles 66
Pseudo-code
1. function Order(items) {
2. this.items = items;
3. this.amount = function() {
4. var total = 0;
5. for(item in this.items) {
6. total += item.value;
7. }
8. return total;
9. }
10. }
Pseudo-code
1. function Order(items) {
2. this.items = items;
3. this.amount = function(currency) {
4. var total = 0;
5. for(item in this.items) {
6. total += item.value;
7. }
8.
9. if(currency == "MMK")
10. return total * getExchangeRate();
11. else
12. return total;
13. }
14. }
Pseudo-code
1. function Order(items) {
2. this.items = items;
3. this.amount = function() {
4. var total = 0;
5. for(item in this.items) {
6. total += item.value;
7. }
8. return total;
9. }
10.
11. this.kyatAmount = function() {
12. var total = this.amount();
13. return total * getExchangeRate();
14. }
15. }
" Inherit
Sub-Class Class "
Class Object
Sub-Class
Object Sub-Class
Class
Pseudo-code
1. function Rectangle () {
2. this.setWidth = function(width) {
3. this.width = width;
4. }
5. this.setHeight = function(height) {
6. this.height = height;
7. }
8. this.area = function() {
9. return this.width * this.height;
10. }
11. }
12.
13. function Square() {
14. Rectangle.call(this);
15. this.setWidth = function(width) {
16. this.width = width;
17. this.height = width;
18. }
19. this.setHeight = this.setWidth;
20. }
" Interface
Interface "
3 Pin Head, 2 Pin Head, USB 2.0 Port, USB 3.0 Port Power Outlet
Interface Single Responsibility Principle
Power Outlet
Port
Support Interface USB Power Outlet
Interface Outlet
Outlet Short Circuit Outlet
Interface Interface
Pseudo-code
1. function Car() {
2. this.engine = function() { ... }
3. this.break = function() { ... }
4. this.playRadio = function() { ... }
5. this.ejectCD = function() { ... }
6. }
Pseudo-code
1. function SpeedControl() {
2. this.engine = function() { ... }
3. this.break = function() { ... }
4. }
5. function AudioControl() {
6. this.playRadio = function() { ... }
7. this.ejectCD = function() { ... }
8. }
9.
10. function Car() {
11. this.speed = new SpeedControl();
12. this.audio = new AudioControl();
13. }
SpeedControl AudioControl
Interface Interface Car
Constructor SpeedControl AudioControl
Maintain Audio
Client Interface
Interface
Interface Segregation Principle
Pseudo-code
1. function PDF() {
2. this.read = function() {
3. // parse and read PDF file
4. }
5. }
6.
7. function Reader() {
8. this.book = new PDF();
9. this.read = this.book.read();
10. }
Pseudo-code
1. function PDF() {
2. this.read = function() {
3. // parse and read PDF file
4. }
5. }
6.
7. function Epub() {
8. this.read = function() {
9. // parse and read epub file
10. }
11. }
12.
13. function Reader(book) {
14. this.book = book;
15. this.read = this.book.read();
16. }
PDF Epub
Low Level Object Reader Hight Level Object
Reader PDF Epub read() Function
PDF Epub
Reader Object PDF Epub Object
Object read() Function Reader PDF
Epub File Format Object Dependency
Inversion Flexible
Pseudo-code
Object Object Detail
Dependency Inversion Principle
Conclusion
Code OOP, SOLID
Code
Code
Reusable Code
Reusable Service
http://pwdbook.com
Rockstar Developer () Service Oriented Architecture 74
Software Solution
- Business Solution
Customer Supplier Order
Payment Stock
Software Solution
SOA Service
Service Solution
SOA () Service Provider (Server), Service
Consumer (Client) Interface (Protocol)
Utility Services
Service Layer Utility Service Database
Service File Read/Write File System
Service User Action Event Log Logging Service
Hardware Resource Service Data Format
Encoding Service
Service
Core Services
Software Solution Common Logic Key Logic
Service Core Service Customer Management Service, Supplier
Management Service, Stock Management Service, Order Management Service, Payment Service
Solution Service
Client Services
Services User Service Client Service
Service Invoice Service
Invoice Document Client
Service Invoice Service Core Service Payment
Rockstar Developer () Service Oriented Architecture 77
Policy Service
Rockstar Developer () Service Oriented Architecture 78
Data Access Services File System I/O Service Database Service Data Access Service
File Read/Write File Format
Data Encode/Decode
Data Model Data Relationship Index
File Data Utility Service Data Access Service
Service
Service
Application Service Application Service
Solution
Business Solution Customer, Supplier, Client, Payment, Order, Stock Service
Social Collaboration Solution Real-time Messaging, Group
Messaging, Contact List Service Requirement
Service
SOA
Software
Utility Layer Core Layer
Development Productivity
SOA Development Productivity
Software Solution
Solution
Developer
Service Developer
Service
Service
Interface
Service Developer
Language Platform
Infrastructure Service Performance
C/C++, Go Language Monitor Service Real-time
Rockstar Developer () Service Oriented Architecture 81
concurrency
NodeJS
Application Service Business Component
Java, .Net
Developer
Development Productivity
Efficiency
Scalability
SOA Service
Deploy Network
Data Access Service Application Service
Monitor Service Monitor
Service Processing Power Data Store Data
Access Service Storage Capacity
Service Setting Hardware
Infrastructure
Service
Web Service
REST JSON
REST
Stateless Service
Server Service
Cache
Client Service
Cache
Identification (ID) ID
Web Technology
URL Web Resource
URL Resource Client Service URL
ID
ID
Web Technology URL
URL Service URL
Professional Web Developer
() REST Service
ID Design ID
Uniform Interface
Data Format
Server Service
Client Service Data Format
Data Format JSON, XML YAML Data Format
Programming Language
Client Service Data Format
Consistency Format
XML-RPC, SOAP Interface
XML Data Format
Code on Demand
Web Service
Code Exchange Standard JavaScript
JSON
JavaScript
1. function Person() {
2. this.fullName = "James Doe";
3. this.age = 32;
4. this.walk = function() {
5. console.log(this.fullName + " is walking.");
6. }
7. }
8.
9. var james = new Person();
10. james.walk(); // => James Doe is walking.
JavaScript
1. var james = {
2. fullName: "James Doe",
3. age: 32,
4. walk: function() {
5. console.log(this.fullName + " is walking.");
6. }
7. }
8.
9. james.walk(); // =>James Doe is walking
Rockstar Developer () Service Oriented Architecture 85
JavaScript
1. var james = {
2. fullName: "James Doe",
3. age: 32,
4. walk: function() {
5. console.log(this.fullName + " is walking.");
6. },
7. address: {
8. street: "52, Main Road",
9. city: "Yangon",
10. },
11. phones: [
12. "123 456 789",
13. "987 654 321"
14. ],
15. children: null
16. }
17.
18. james.address.city; // => Yangon
19. james.phones[0]; // => 987 654 321
Service Design
Design Language
Conclusion
Software Development 3-Tires Architecture, Modular Design, Layered System, Model-View-
Controller Architecture
Software Solution
Project Management
Code
Manual
Code
Code Manual
Ubuntu Linux ()
Ubuntu Linux Installation System
Configuration Development Environment
http://u4ubook.com
Rockstar Developer () Version Control System 89
".. "
" "
"... Demo
"
"...
"
"project-latest . .. project-real-latest
Version
"
Version
Code
Version
Branch
Code master Code Base Development Branch
Development Branch
Version
Development Branch master Code Base
Merge
master/trunk branch
Code Base master branch () trunk
Version
Version Commit
Original Repository
Local Repository Code
Version Version
5.3 Git
Git Linux Kernel Linus Torvalds ()
Distributed VCS Open Source Software VCS
Linus Torvalds Linux Kernel Developer BitKeeper DVCS
Linux Kernel
Rockstar Developer () Version Control System 96
1. Distributed VCS
2.
3. Data
http://msysgit.github.io/
Install
Git Command Line Graphical User
Rockstar Developer () Version Control System 97
Command Command
Operating System Install Git
Version, File Permission
Configuration
Git Install Email
Configuration Global Config Local Config
Configuration Git Repository
Setting Global Config Repository
Setting Local Config
Configuration Setting
Configuration OS Install
Setting
git config
Command Email Global
Config Command
http://git-scm.com/docs/git-config
Initializing a Repository
Git Version Source Code Directory Git
Repository git init Command
$ git init
Branch Merge
Shell Script hooks
Config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
Git
Configuration Setting
HEAD
Branch
Version Commit
HEAD Branch Version
Git Repository
$ git status
On branch master
Initial commit
Untracked files:
(use "git add <file>..." to include in what will be committed)
index.html
script.js
style.css
nothing added to commit but untracked files present (use "git add" to track)
$ git add .
$ git status
On branch master
Initial commit
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: index.html
no changes added to commit (use "git add" and/or "git commit -a")
$ git log
commit f76103d35ad7b2a2641bf16d1baf6de27a5981cf
Author: Ei Maung <eimg@fairwayweb.com>
Date: Tue Mar 17 15:42:02 2015 +0630
Updated index.html
commit 11bf458a3a3cc45e65e5c20e16c59d92d66038e7
Author: Ei Maung <eimg@fairwayweb.com>
Date: Tue Mar 17 12:48:56 2015 +0630
First commit
--pretty=oneline
Log
Commit online Format
Rockstar Developer () Version Control System 103
Commit Tag
$ git tag v1
$ git checkout v1
$ git branch
* master
Rockstar Developer () Version Control System 105
dev
* master
$ git branch
* dev
master
Branch Branch
Short Cut
$ git branch
* beta
dev
master
beta Branch
Branch git branch -d Option
Merge Conflicts
Branch Merge Conflict Merge
Branch
master
Branch script.js Commit
Auto-merging script.js
CONFLICT (content): Merge conflict in script.js
Automatic merge failed; fix conflicts and then commit the result.
<<<<<<< HEAD
var app = {}
=======
var app = []
>>>>>>> beta
Conflict
master script.js Code beta script.js
Code Code
Commit Conflict Resolve
Log
Clone Repository
Repository git clone git clone
Repository Network Repository
git clone Repository
$ cd ~
$ git clone /opt/lampp/htdocs/project
$ ls project
$ cd project
$ git log pretty=oneline
$ git branch
* master
$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/beta
remotes/origin/master
$ git branch
* beta
master
$ cd /opt/lampp/htdocs/project
$ touch app.js
$ git add app.js
$ git commit -m "Added app.js"
Repository Commit
Log
Commit git log -3 Option
Commit () -3
$ cd ~/project
$ git log --pretty=oneline -3
$ git remote
origin
origin origin
git remote show origin Run
* remote origin
Fetch URL: /opt/lampp/htdocs/project
Push URL: /opt/lampp/htdocs/project
teamb
origin
origin Update
origin
Centralize Repository
Git Repository Centralize Repository Developer
Working Directory Version Branch
Bare Repository () Bare
Repository Directory git
init --bare Option Bare Repository
$ cd ~
$ git clone --bare /opt/lampp/htdocs/project
$ git init
To /opt/lampp/htdocs/rockstar
! [rejected] master -> master (fetch first)
error: failed to push some refs to '/opt/lampp/htdocs/rockstar'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
Centralize Repository
Version
Centralize Repository Update Update
git pull
Other
Git
Commit
Commit --amend Option
Mac Linux
http://git-scm.com/downloads/guis
Software Versioning
Software Version
Commit Version
Commit Hash Version
Commit Version Git Tag
Versioning
Version
Version (.)
Version
0.1.1, 0.1.2, 0.1.3 PATCH
Version 0.2.0
0.2.0
0.2.1, 0.2.2, 0.2.3
0.3.0, 0.3.2, 0.3.2, 0.4.0, 0.4.1
MINOR Version MINOR Version
PATCH Version
MAJOR Version
1.0.0
1.0.0-pre-alpha
1.0.0-alpha User
1.0.0-beta pre-alpha, alpha
beta PRE-RELEASE PATCH
1.0.0-beta.1, 1.0.0-beta.2
Rockstar Developer () Version Control System 121
1.0.0-rc
rc Release Candidate
Release
1.0.0-rc PRE-
RELEASE Version 1.0.0
() Software 2.0.0
MAJOR Version
Software Version
- Flash MX, Photoshop CS, Windows XP
Windows 2000, Ubuntu 14.04 Internal Version
Java7
Internal Version Java 1.7 Version
Conclusion
Software Project Team
Version Control System Centralize Code
Base Project VCS
http://eimaung.com/courses
Rockstar Developer () Issue Tracking System 124
Team
Software Development Team
() Source Control
() Bug Database
Productivity
Bug
Bug
Bug Software Release
Up-to-date Schedule Software
() Working Condition
Developer Private
Office
Developer
Software Developer
Working Condition
() Best Tools
IDE
Commercial Database System
Tool
() Tester
() Test
Method Tester System Test
Software Specification
Tester Software Quality Quality
Assurance Engineer Joel Spolsky Team
Developer Tester
Article () Article
http://www.joelonsoftware.com/articles/fog0000000043.html
Bug Developer
Bug
Minor Bug
Bug Release
Bug
Software Developer
Bug Developer But
Developer Centralize Database
Developer Manager, Tester User Bug
Bug Database
Bug Bug
Reproducing Steps
Bug
Bug
Bug
Expected behavior Buggy behavior
Expected "Mobile Phone Category
Mobile Phone " Bug "Mobile Phone Category
Laptop "
Laptop Mobile Phone
Rockstar Developer () Issue Tracking System 129
Assigned
Bug
Team Leader Assigned
Bug Bug
Status Bug
Bug Behavior
Status
Feature
() Bug Database
Bug Screenshot
Bug Bug
Bug OS Version, Browser Version
Software Version Developer
Bug Category
Bug Priority
Bug
Status Fixed
Software
( Hardware Software
) Status Won't Fix
Bug Status
Bug
Bug
Bug
Bug Developer
Bug Database
Developer Bug Bug Database
Marketing Staff
Bug Database
Issue
Assign
Issue Tracking System Bug Database
Technician
Workflow
Software Project
Bug Feature Customer Support Request
Bug Database Issue Tracking System
Developer "
Email "
Software Project
Specification
Specification
Software Feature
Feature Issue
Tracking System
Issue Tracking
Log Assign Assign
Notify Issue
Notify
Rockstar Developer () Issue Tracking System 136
Issue
Project Issue
Field
Progress Percentage
Issue
Issue
Chart Graph
Issue Tracking System Project Management
System Issue
Project
Project Management System
Conclusion
Software Team Issue Tracking System
Issue Issue
Issue
Issue
Issue
Time Management Release Schedule Management
http://eimaung.com/courses
Rockstar Developer () Team Collaboration 140
( ) Team Collaboration
1. Adaptive Planning
Plan
2. Evolutionary Development Product
3. Early Delivery Product
Product
4. Continuous Improvement
5. Rapid and Flexible Response to Change Requirement
Product
Requirement Specification
Software Project Team
Specification
Specification Agile
Adaptive Planning Flexible Response to Change
Up-to-date Specification Spec
Team
Developer
Collaboration Teamwork
Agile Principle Software Project Collaboration Agile
Principle
7.1 Specification
Team Collaboration Specification
Spec Specification
() Spec
Software Function Specification
Implementation Detail Spec
Spec
Software Code
Software Spec
Function Specification
Software Documentation Documentation
Spec End-user
Documentation
Function Spec
"Project Manager
Username/Password Login
Dashboard Project Project
Project Issue Status Filter Option
Assigned Assign
Issue "
Dashboard
Multiple Project
Issue List, Issue Filter Issue
Status
User Story
Spec
Software
Account Recover
Remember Me Option
Account Register Page
"
Screen
Todo Todo
Developer ()
Expert " "
Up-to-date Spec
Requirement
Update
Spec
Task Bar
Progress Bar
Task Issue Module Development
Testing Task
http://teamgantt.com/
Product Owner
Stakeholder (Customer, Higher Management) Product
Stakeholder
Product Owner
Stakeholder
Development Team Team Project
Rockstar Developer () Team Collaboration 147
Sprint
SCRUM Sprint Iterative Development Model
Software
Sprint
()
Team
() ()
() ()
Sprint Feature
Code Quality Tracer Bullet Code
Refactoring Sprint
Sprint Spike Tracer Bullet
Meeting Feature
Sprint Backlog Implementation Plan
Development Team
Feature Review
Feature Demo
Sprint Developer
Sprint
Sprint
Task Board
Backlog Task Task Board Task Board
Column White Borad Sprint Board
Source Wikipedia
Done Column
Trello
Online Tool Software
White Board User Story Screenshot
Attach User Story Checklist (Task List)
Sticky Note User Story Label
User Story Comment
White Board - Board
Trello
http://trello.com/
SCRUM Kanban
SCRUM Development Focus Process Management Kanban
Business Operation
Process Management
Task Board Kanban Development
Specification Data Analyst Deployment
Software Development Work-flow Task Board
Kanban Sprint Column Task
Doing Column User Story ()
Rockstar Developer () Team Collaboration 152
Task List Google Keep, Evernote, Remember The Milk Task List Manager
Text Text
Text Task List
Source Code Code Base Pull () Clone
Source Code Task List Task
List Source Code Task List Version Control
Plain Text
Design:
# TODO
[-] Two column layout for issue detail page
Main contents such as category, subject and etc. should be in left column.
[-] Issue list table design
Issue list table should highlight priority and severity
Coding:
# TODO
[-] Issue form validation @today
category, subject, reproduction steps, severity and priority are mandatory
[-] SQL Injection filter in issue submission @due (15-03-28)
[-] Issue log in issue details
# DONE
[+] Issue list Sorting (15-03-27 23:35)
# CANCELLED
[x] Issue delete on issue detail (15-03-27 23:46)
Testing:
# TODO
[-] Desktop cross browser test
We will only support IE 9 and above.
Tag
Task
Rockstar Developer () Team Collaboration 154
Text Editor
() IDE Syntax Highlight
IDE () Text
Editor Task Management
https://github.com/aziz/PlainTasks
https://github.com/jonathandelgado/SublimeTodoReview
Code Review
Rockstar Developer () Team Collaboration 156
Pair Programming
Pair Programming
Agile Development Extreme Programming
Programmer
Code Review
Code Driver Review Navigator
Navigator
Code Driver
Rockstar Developer () Team Collaboration 157
Code
Navigator
Code Quality
Pair Programming
Pair Programming
Developer Level
Driver Driver
Developer
Pair
Conclusion
Collaboration Team
Remote Team SCRUM Pair Programming
Issue Tracking System
Project
Management Software Team
Issue Tracking Task List
Agile Team
Rockstar Developer () Team Collaboration 158
Software Project
Development Workflow
Automation
Automate
Manual
http://pwdbook.com
Rockstar Developer () Development Workflow Automation 160
1. Scaffolding
2. Package Management
3. Build
4. Deployment
8.1 Scaffolding
Software Project
Directory Structure Source Code
Web Page Structure
WebPage
css
responsive.css
style.css
img
logo.png
js
app.js
jquery.js
index.html
HTML
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>Document Title</title>
6. <link rel="stylesheet" href="css/style.css">
7. </head>
Rockstar Developer () Development Workflow Automation 161
8. <body>
9.
10. <script src="js/jquery.js"></script>
11. <script src="js/app.js"></script>
12. </body>
13. </html>
CSS
1. html, body {
2. margin: 0;
3. padding: 0;
4. }
5.
6. article, aside, details, figcaption, figure, footer,
7. header, hgroup, main, menu, nav, section, summary {
8. display: block;
9. }
10.
11. a:active, a:hover {
12. outline: 0;
13. }
14.
15. img {
16. border: 0;
17. }
18.
19. table {
20. border-collapse: collapse;
21. border-spacing: 0;
22. }
HTML5-boilerplate
css
main.css
normalize.css
img
js
vendor
jquery-1.11.2.min.js
modernizr-2.8.3.min.js
main.js
plugins.js
.htaccess
.gitignore
404.html
favicon.ico
index.html
HTML
1. <!doctype html>
2. <html class="no-js" lang="">
3. <head>
4. <meta charset="utf-8">
5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
6. <title></title>
7. <meta name="viewport" content="width=device-width, initial-scale=1">
8.
9. <link rel="stylesheet" href="css/normalize.css">
10. <link rel="stylesheet" href="css/main.css">
11. <script src="js/vendor/modernizr-2.8.3.min.js"></script>
12. </head>
13. <body>
14. <!--[if lt IE 8]>
15. <p class="browserupgrade">You are using an <strong>outdated</strong>
browser. Please <a href="http://browsehappy.com/">upgrade your
browser</a> to improve your experience.</p>
16. <![endif]-->
17.
18. <p>Hello world! This is HTML5 Boilerplate.</p>
19.
20. <script src="//ajax.googleapis.com/ajax/libs/jquery.min.js"></script>
21. <script>window.jQuery || document.write('<script
src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
22. <script src="js/plugins.js"></script>
23. <script src="js/main.js"></script>
24.
25. <script>
26. (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
Rockstar Developer () Development Workflow Automation 163
27. e=o.createElement(i);r=o.getElementsByTagName(i)[0];
28. e.src='//www.google-analytics.com/analytics.js';
29. r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
30. ga('create','UA-XXXXX-X','auto');ga('send','pageview');
31 </script>
32. </body>
33. </html>
web-starter-kit
app
fonts
images
scripts
main.js
styles
components
_h5bp.scss
main.scss
basic.html
favicon.ico
index.html
manifest.json
manifest.webapp
Rockstar Developer () Development Workflow Automation 164
gulpfile.js
package.json
Ruby on Rails, CakePHP, Django, Symfony, ASP.NET MVC, ExpressJS Framework Scaffold
Generator Generator Boilerplate
MVC Structure CRUD
Modern Web App Yeomen
Scaffold Generator
Yeomen Boilerplate Code
Generator
Rockstar Developer () Development Workflow Automation 165
8.2 Yeomen
Yeomen NodeJS Scaffold Generator JavaScript Web App
Code Generator Project
Yeomen NodeJS NodeJS Installer nodejs.org
Download Windows, Mac, Linux OS Installer
Ubuntu Linux Download Install
npm install yo
NPM Yeoman Scaffold Generator Download Install
Install Directory Install
Directory
NodeJS Global Directory Install -g Option
-g Option NPM Yeoman NodeJS Global Directory
Install Install
Command
Command Operating System, Install
Tool Version File Permission
Error Message Instruction
Rockstar Developer () Development Workflow Automation 166
$ yo
? 'Allo Ei! What would you like to do? (Use arrow keys)
Run a generator
Backbone
Webapp
Mocha
Update your generators
Install a generator
(Move up and down to reveal more choices)
yo Command Install
Generator
Generator Generate Webapp Enter
Make sure you are in the directory you want to scaffold into.
This generator can also be run with: yo webapp
_-----_
| | .--------------------------.
|--(o)--| | Welcome to Yeoman, |
`--------- | ladies and gentlemen! |
( _U`_ ) '--------------------------'
/___A___\
| ~ |
__'.___.'__
` | Y `
I'm all done. Running bower install & npm install for you to install the
required
dependencies. If this fails, try running the command yourself.
create test/bower.json
create test/.bowerrc
create test/spec/test.js
create test/index.html
bower chai#~1.8.0 cached git://github.com/chaijs/chai.git#1.8.1
bower chai#~1.8.0 validate 1.8.1 against git://github.com/chaijs/chai.git
...
Boilerplate
Library Download Keyboard Ctrl+C
bower install npm install Command Run
Code Base Structure
webapp
app
images
scripts
main.js
styles
main.css
favicon.ico
index.html
robots.txt
test
bower.json
.gitignore
Gruntfile.js
$ yo backbone
$ yo angular
$ yo php
$ yo wordpress
$ yo laravel
$ yo django
$ yo firefox-os
Generate
Generator Install
Generator yo generator
_-----_
| | .--------------------------.
|--(o)--| | Create your own Yeoman |
`--------- | generator with |
( _U`_ ) | superpowers! |
/___A___\ '--------------------------'
| ~ |
__'.___.'__
` | Y `
generator-tinymvc
app
templates
index.js
node_modules
test
test-app.js
Rockstar Developer () Development Workflow Automation 170
.gitignore
.jshintrc
package.json
generator-tinymvc
Generator Boilerplate
Structure app Directory index.js
app Directory Source Code Template index.js
Generator Script app/template Directory index.html
css/style.css Directory Structure
generator-tinymvc
app
templates
css
style.css
index.html
index.js
node_modules
test
test-app.js
.gitignore
.jshintrc
package.json
index.js Code
JavaScript
$ cd generator-tinymvc
$ sudo npm link
npm link Command Generator Directory Symbolic Link (Shortcut) NodeJS Package
Directory generator-tinymvc
NodeJS Package Yeoman Generator
$ yo tinymvc
create css/style.css
create index.html
tinymvc
css
style.css
index.html
css/style.css index.html
Source Code Boilerplate
Yeoman Generator
http://yeoman.io/authoring/
Rockstar Developer () Development Workflow Automation 172
Package Package
jQuery UI jQuery
BackboneJS jQuery UnderscoreJS Package
Dependency
$ npm list -g
/usr/lib
generator-generator@0.6.1
chalk@1.0.0
ansi-styles@2.0.1
escape-string-regexp@1.0.3
has-ansi@1.0.3
ansi-regex@1.1.1
get-stdin@4.0.1
strip-ansi@2.0.1
ansi-regex@1.1.1
supports-color@1.3.1
github@0.2.3
lodash@2.4.1
npm-name@1.0.4
unbuild generator-tinymvc@0.0.0
8.4 Bower
NPM NodeJS Package Manager NodeJS
Package Web App Package Bower
Package Manager Yeoman Install
Bower
Install Install
jquery#2.1.3 bower_components/jquery
myapp
bower_components
jquery
bower.json
dist
jquery.js
jquery.min.js
jquery.min.map
MIT-LICENSE.txt
src
css
style.css
index.html
http://bower.io/search/
jquery-voter#143a070c8a bower_components/jquery-voter
Rockstar Developer () Development Workflow Automation 175
GitHub Handle
GitHub Username/Git Repo Name GitHub
Website Package Install
Package URL
Install
bower .vimrc#* install .vimrc#e-tag:1206bc
.vimrc#e-tag:1206bc-5b bower_components/.vimrc
bower jquery#>= 1.9.1 install jquery#2.1.3
bower bootstrap#~3.3.4 install bootstrap#3.3.4
jquery#2.1.3 bower_components/jquery
bootstrap#3.3.4 bower_components/bootstrap
jquery#2.1.3
Directory Structure
mypackage
bower_components
bootstrap
bower.json
dist
fonts
js
jquery
bower.json
dist
src
mypackage
bower_components
bootstrap
bower.json
dist
fonts
js
jquery
bower.json
dist
src
app.js
index.html
$ bower init
? name: mypackage
? version: 0.1.0
? description: Bower package test
? main file: app.js
? authors: Ei Maung <eimg@fairwayweb.com>
? set currently installed components as dependencies?: Yes
{
name: 'mypackage',
version: '0.1.0',
authors: [
'Ei Maung <eimg@fairwayweb.com>'
],
description: 'Bower package test',
main: 'app.js',
keywords: [
'test'
],
dependencies: {
bootstrap: '~3.3.4',
"jquery": '~2.1.3'
}
}
name
JSON
"dependencies": {
"bootstrap": "~3.3.4",
"jquery": "~2.1.3" ,
"underscore": "~1.8.2"
}
mypackage
Package
Git
Repo
Bower Package Registration
Package Register
Package Register Unique Name Register
bower install
8.5 Build
Software Project Development Production
Software Development Stage Error Message
Error Message
Production Stage Error Message
Fatal Error Warning Notice
Build
Development Code Production
Software Build
Build
Build Process Project
Web App Build
1. Run tests
2. Compile preprocessor
3. Generate static template
4. Lint JavaScript
5. Minify JavaScript, CSS and HTML
6. Concatenate JavaScript and CSS
7. Optimize Images
8. Create distribution package
Rockstar Developer () Development Workflow Automation 180
Package
() Software Team ()
Build () Build
Build
Build
Build
Manual
Automate
8.6 Grunt
Grunt Automate
Task Runner Tool NodeJS Tool
Yeoman Install Install
Install
JSON
1. {
2. "name": "my-project-name",
3. "version": "0.1.0",
4. "devDependencies": {
5. "grunt": "~0.4.5"
6. }
7. }
my-project-name devDependencies
grunt 0.4.5 Dependency Build
Task Plugin
Plugin Install
JavaScript Code Minify Grunt Plugin Install
JSON
"devDependencies": {
"grunt": "^0.4.5",
"grunt-contrib-uglify": "^0.5.0"
}
JavaScript
1. module.exports = function(grunt) {
2.
3. grunt.initConfig({
4. uglify: {
5. build: {
6. files: {
7. 'js/app.min.js': ['js/mobile.js', 'js/app.js']
8. }
9. }
10. }
Rockstar Developer () Development Workflow Automation 182
11. });
12.
13. grunt.loadNpmTasks('grunt-contrib-uglify');
14. grunt.registerTask('default', ['uglify']);
15.
16. };
my-project
js
app.js
mobile.js
node_modules
grunt
grunt-contrib-uglify
Gruntfile.js
package.json
$ grunt
my-project
js
app.js
app.min.js
mobile.js
node_modules
grunt
grunt-contrib-uglify
Gruntfile.js
package.json
Rockstar Developer () Development Workflow Automation 183
http://gruntjs.com/plugins
( (.) - Web App Development Workflow with Yeoman, Bower and Grunt
Source yeoman.io
8.7 Deployment
Software Deploy
Software
Software Deploy
Software Infrastructure
Server, Network System Requirement Infrastructure
Architecture Design
Enterprise IT Architecture
Software Software
Consumer Software
Build User
Distribution Method App Store
Website Download Software
API Back-end Server Environment
Server Environment Cloud Service Provider
Production Server Setup
Setup
Server Environment Build Software
Publish FTP Software Build
Software Production Server Copy
.) Software
Connection
.) Deploy
Version 0.1.0 Deploy
Version 0.1.1 Deploy 0.1.0
0.1.1 Software
.)
Compress Compression Algorithm
Size 200% 400% Deployment
Compress Server Copy Compress
Copy Decompress
.) Manual Deploy
Deploy Source Code
Deploy
Production Server
Local Code Base
Production Version Development Version
Deployment Build
Software Server
Git Workflow
Rockstar Developer () Development Workflow Automation 186
https://github.com/apenwarr/git-subtree
Commit Build
Developer Code
Commit
Commit
Developer
Commit
Build
YAML
language: node_js
node_js:
- 0.10
- 0.8
- 0.6
services:
- mongodb
before_script:
- npm install
- bower install
notifications:
email:
- "james@gmail.com"
- "john@gmail.com"
JSON
scripts {
"test": "grunt"
}
YAML
after_success:
- git remote add deploy git:/path/to/repo/
- git push deploy
VCS Commit
Build Deploy
Continuous Integration
Conclusion
Tool Web App Project
Tool Software Project Language,
Framework Scaffolding, Package Management, Build Tool CI Tool
Ruby on Rails, Django, ASP.NET MVC, Laravel, Synfony, CakePHP Framework Scaffolding
Ubuntu Linux ()
Ubuntu Linux Installation System
Configuration Development Environment
http://u4ubook.com
Rockstar Developer () BackboneJS (Client-Side MVC) 193
BackboneJS MVC
Model-View-Collection Data
Model UI View
Collection
Model Model Collection Controller
User Event
View
Directory Structure
bbApp
app
bower_components
backbone
jquery
lodash
modernizr
underscore
images
scripts
vendor
main.js
styles
main.css
404.html
favicon.ico
index.html
node_modules
test
bower.json
Gruntfile.js
package.json
Code Code
JavaScript
1. var Issue = {
2. data: {
3. subject: "Drop down menu not working",
4. reproduce: " ... ",
5. priority: 3,
6. status: 1
7. },
Rockstar Developer () BackboneJS (Client-Side MVC) 197
8. changeStatus: function(value) {
9. this.data.status = value;
10. }
11. }
JavaScript
JavaScript
JavaScript
issueTwo.get("priority"); // => 3
JavaScript
JavaScript
issueTwo.set({detail: "<script>alert(1)</script>"});
issueTwo.escape("detail"); // => <script>alert(1)</script>
JavaScript
JavaScript
issueTwo.unset("subject");
Rockstar Developer () BackboneJS (Client-Side MVC) 199
JavaScript
JavaScript
console.log(issueTwo.cid); // => c1
JavaScript
issueTwo.toJSON();
// => { subject: "Dropdown menu not working", priority: 3, status: 1 }
changedAttributes() save()
Data
JavaScript
4. });
Server
model
Collection Model Collection
Model Object JavaScript Array Backbone
model Model Object
Collection Constructor Backbone Collection
JavaScript
JavaScript
Issues.add([issueOne, issueTwo]);
set() reset()
Model Model Model
Model Model
Model Update Model
JavaScript
Issues.get("c1");
JavaScript
Issues.at(2);
JavaScript
JavaScript
Issues.comparator = "priority";
JavaScript
Issues.pluck("subject");
JavaScript
Issues.where({status: 2});
clone() Collection
fetch() URL
Server Model
set() Function Collection Update
GET Request Method
Request Method
Function Property UnderscoreJS Array Function Collection
Underscore Function
JavaScript
Issues.each(function(model) {
console.log( model.get("subject") );
});
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
() Issue Model Constructor
() IssueList Collection Constructor ()
IssueList Constructor Issues Collection Object
( ) Issue Constructor Model Object
Model Object add() Function ()
Issues Collection () Issues
each() Loop Model subject jQuery List UI
Backbone
View
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
render() Default
remove() View
JavaScript
JavaScript
Event
destroy Model Event
request Server Event
sync Server
Event
error Server Event
invalid Model Validation Event
all Event Event
JavaScript
IssueOne.trigger("change");
HTML
ID #new
New Issue Form
HTML
5. <div class="modal-header">
6. <button type="button" class="close" data-dismiss="modal">
7. <span aria-hidden="true">×</span>
8. </button>
9. <h4 class="modal-title">New Issue</h4>
10. </div>
11.
12. <div class="modal-body">
13.
14. <div class="form-group">
15. <input class="form-control" type="text"
id="subject" placeholder="Subject">
16. </div>
17.
18. <div class="form-group">
19. <select class="form-control" id="priority">
20. <option value="-1">-- Priority --</option>
21. <option value="0">Normal</option>
22. <option value="1">Important</option>
23. <option value="2">Critical</option>
24. </select>
25. </div>
26.
27. <div class="form-group">
28. <select class="form-control" id="severity">
29. <option value="-1">-- Severity --</option>
30. <option value="0">Minor</option>
31. <option value="1">Major</option>
32. <option value="2">Crash</option>
33. </select>
34. </div>
35.
36. <div class="form-group">
37. <input type="text" class="form-control"
id="assigned-to" placeholder="Assigned To">
38. </div>
39.
40. <div class="form-group">
41. <select class="form-control" id="status">
42. <option value="-1">-- Status --</option>
43. <option value="0">Assigned</option>
44. <option value="1">WIP</option>
45. <option value="2">Done</option>
46. <option value="3">Close</option>
47. </select>
48. </div>
49.
50. </div>
51.
52. <div class="modal-footer">
53. <button class="btn btn-primary" id="submit">Submit Issue</button>
54. </div>
55.
56. </div>
57. </div>
58. </div>
Template
JavaScript User
Template Structure Template
Data Underscore Template Function HTML Output
JavaScript
1. var config = {
2. priority: ['Normal', 'Important', 'Urgent'],
3. severity: ['Minor', 'Major', 'Crash'],
4. status: ['Assigned', 'Doing', 'Done', 'Close']
5. };
12. }
13. });
JavaScript
JavaScript
23.
24. changeStatus: function() {
25. this.model.changeStatus( this.$('.change-status').val() );
26. },
27.
28. delSelf: function() {
29. this.model.destroy();
30. }
31. });
JavaScript
JavaScript
1. $(function() {
2. new AppView();
3. });
https://github.com/eimg/backbone-example/archive/master.zip
Conclusion
Backbone
JavaScript MVC Framework
Backbone AngularJS
Framework
Framework
Angular Opinionated Framework Opinionated Framework Code
Framework Code Maintenance
Input/Output Device
http://eimaung.com/courses
Rockstar Developer () NodeJS (Server-side JavaScript) 224
Ryan Dahl System Engineer NodeJS
JavaScript Client-side Scripting Language General
Purpose Programing Language Web Application
Application
Development Platform NodeJS Web Application
Server-side Web Developer
Server-side Client-side JavaScript
Server-side Language Client-side
Language NodeJS Client-
side Server-side JavaScript
Language
NodeJS Community
NodeJS io.js NodeJS Major Version
NodeJS 4.0 Joyent Samsaung
Samsaung
NodeJS Version 6.2.2
Size Instruction
() CPU
Non-blocking I/O
Inter-process Communication
Run Operating System Memory Space System
Resource Process Instruction
Process Non-blocking I/O
Process
Memory I/O Process Process
Process
Process I/O
Process Process
I/O Process
Rockstar Developer () NodeJS (Server-side JavaScript) 227
Process
Inter-process Communication (IPC) Non-blocking I/O
IPC
Message Passing, Message Queue, Socket, Memory Mapped File
IPC
Non-blocking I/O
Time Sharing Thread
Thread
Process Instruction
Process Process Non-blocking
I/O
Thread Process
IPC
Implement
Language Platform Thread API
Source Wikipedia
Thread
Hang
Resource Thread
Process I/O
Callback Function I/O
Callback Function Process
I/O
PHP
$data = file("bigfile.csv");
print_r($data);
// other processes
JavaScript
1. var fs = require("fs");
2.
3. fs.readFile("bigfile.csv", "utf8", function(err, data) {
4. console.log(data)
5. });
6.
7. // other processes
Rockstar Developer () NodeJS (Server-side JavaScript) 229
Pseudo-code
issue.on('assigned', function() {
// send notification to assignee
});
issue.on('done', function() {
// send notification to submitter
});
issue.on('close', function() {
// archive issue
});
Command Code
Command Code
$ node
> console.log("Hello, World!");
Hello, World!
undefined
undefined
> area(8)
200.96
Hello, World
JavaScript
console.log(process.args)
process.args script.js
Arguments Run
JavaScript
console.log(process.args.slice(2))
script.js
JavaScript
1. var pi = 3.14;
2. function area(r) {
3. var a = pi * r * r;
4. debugger;
5. return a;
6. }
7.
8. console.log( area(8) );
9. console.log( area(12) );
debug>
() Debug Console
cont () c Command
debug> c
break in script.js:4
2 function area(r) {
3 var a = pi * r * r;
Rockstar Developer () NodeJS (Server-side JavaScript) 233
4 debugger;
5 return a;
6 }
debug>
debugger ()
repl Command JavaScript Code Run
Debug Console repl Console Variable
debug> repl
> a
200.96
debug>
Variable a a
200.96 repl Console Debug Console
Ctrl+C Debug Console Break
Function Debug out () o
Command
debug> o
break in script.js:8
6 }
7
8 console.log( area(8) );
9 console.log( area(12) );
10
debug>
Function ()
next () n Command
Rockstar Developer () NodeJS (Server-side JavaScript) 234
debug> n
< 200.96
break in script.js:9
7
8 console.log( area(8) );
9 console.log( area(12) );
10
11 });
debug>
() n Command Debug
Function
step () s Command
debug> s
break in node.js:205
203 startup.globalConsole = function() {
204 global.__defineGetter__('console', function() {
205 return NativeModule.require('console');
206 });
207 };
debug>
debug> o
break in script.js:9
7
8 console.log( area(8) );
9 console.log( area(12) );
10
11 });
debug>
()
cont () c
Rockstar Developer () NodeJS (Server-side JavaScript) 235
debug> c
break in script.js:4
2 function area(r) {
3 var a = pi * r * r;
4 debugger;
5 return a;
6 }
debug>
debug> repl
> a
452.15999999999997
debug> c
< 452.15999999999997
program terminated
debug>
a 452.159
Debug Mode
c Command
program terminated Message
cont, c
next, n
step, s Step In Platform Debug Step In
Function
out, o Step Out
Platform Debug Step Out
Rockstar Developer () NodeJS (Server-side JavaScript) 236
Function
Debug
pause
Node Inspector
Chromium Browser Dev Tool Firebug, Chrome Dev
Tool Debug Tool
Node Inspector JavaScript Code Debug
node-debug
Command
$ node-debug script.js
debugger listening on port 5858
Node Inspector is now available from http://127.0.0.1:8080/debug?port=5858
Debugging `script.js`
HTML
<script src="circle.js"></script>
<script src="square.js"></script>
<script src="area.js"></script>
CommonJS, RequireJS
NodeJS JavaScript Code JavaScript Module
require() Function
JavaScript
JavaScript
()
JavaScript
1. module.exports = {
2. circle: function (r) {
3. var pi = 3.14;
4. return pi * r * r;
5. },
6.
7. square: function (w, h) {
8. return w * h;
9. }
10. }
Pseudo-code
JavaScript
JavaScript
var fs = require("fs");
Function
fs.exists() Callback
JavaScript
fs.exists("path/to/file", function(result) {
if(result) console.log("File exists!");
});
fs.rename() Parameter
Callback
JavaScript
JavaScript
JavaScript
fs.writeFile() () Content
Content Callback Function
JavaScript
fs.appendFile() Content
writeFile() Content Callback Function
writeFile() Content appendFile()
JavaScript
JavaScript
JavaScript
path.basename() Path
JavaScript
JavaScript
JavaScript
path.parse("/path/to/file.csv");
{
root: "/",
dir: "/path/to",
base: "file.csv",
ext: ".csv",
name: "file"
}
JavaScript
path.format({
root: "/",
dir: "/path/to",
base: "file.csv",
ext: ".csv",
name: "file"
});
// => /path/to/file.csv
Function
File System Module
Path Module
https://nodejs.org/api/fs.html
https://nodejs.org/api/path.html
HTTP Module
NodeJS HTTP Module HTTP Server HTTP Client
JavaScript
Server
http.listen() Function listen() Function
Server Port 8080
HTTP Server Code node Command Run HTTP Server Port
8080 Web Browser localhost:8080 Request
Hello, World!
Response Body
Request
HTTP Protocol
Rockstar Developer () NodeJS (Server-side JavaScript) 244
JavaScript
JavaScript
JavaScript
1. http.get("http://www.example.com/", function(res) {
2. res.setEncoding("utf8");
3. res.on("data", function (chunk) {
4. console.log(chunk);
5. });
6. });
JavaScript
1. var options = {
2. hostname: "www.example.com",
3. port: 80,
4. path: "/api",
5. method: "POST"
6. };
7.
Rockstar Developer () NodeJS (Server-side JavaScript) 246
JavaScript
{ protocol: 'http:',
slashes: true,
auth: null,
host: 'example.com:8080',
port: '8080',
hostname: 'example.com',
hash: '#two',
search: '?q=keywords',
query: 'q=keywords',
pathname: '/foo/bar.html',
path: '/foo/bar.html?q=keywords',
href: 'http://example.com:8080/foo/bar.html?q=keywords#two' }
Rockstar Developer () NodeJS (Server-side JavaScript) 247
JavaScript
url.format({
protocol: 'http',
hostname:'example.com',
port: 8080,
pathname: '/foo/bar.html'
});
'http://example.com:8080/foo/bar.html'
JavaScript
'foo=bar&baz=qux&baz=quux'
JavaScript
querystring.parse('foo=bar&baz=qux&baz=quux')
JavaScript
JavaScript
// addresses: 93.184.216.34
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
// eJzzSM3JyddRCM8vyklRBAAfngRq
JavaScript
// Hello, World!
https://nodejs.org/api/
Third-party Modules
Build-in Module Third-party Module NPM Install
MySQL Database NodeJS
Node MySQL Module NPM Install
JavaScript
JavaScript
https://www.npmjs.com/package/mysql
Rockstar Developer () NodeJS (Server-side JavaScript) 253
Database MongoDB
Third-party Module Module ExpressJS,
Grunt, Bower, Yeoman, Cordova, LESS, CoffeeScript, Jade, Karma Module
Yeoman, Bower Grunt () ExpressJS
() Cordova
JavaScript
14.
15. setTimeout(function() {
16. self.emit('close', station);
17. }, 10000);
18. };
19.
20. util.inherits(Radio, EventEmitter);
21. module.exports = Radio;
Inherit
Radio Object emit() Function
Module
JavaScript
App
$ node app.js
Conclusion
NodeJS () JavaScript
Non-blocking I/O
App Non-blocking I/O
Thread Process
App
Data
Database Terabyte
Data
http://eimaung.com/courses
Rockstar Developer () MongoDB (NoSQL Database) 258
MongoDB BSON
JSON Data
Format Administration Shell JavaScript
Ajax, HTML5, NodeJS Software Development
JavaScript Database
Software Development
11.1 NoSQL
Relational Database Management System (RDBMS) MySQL, Oracle, MSSQL Database
() Data Model
Schema Data Data Structure
Source thoughtworks.com
Rockstar Developer () MongoDB (NoSQL Database) 259
RDBMS Database
Data
RDBMS
Scalability
Software Distributed Software
App
Database
Scale
Release
App
Infrastructural
Scale Up
Scale Up
Down
Scale Down Scale Up / Scale Down
Relationship
Source couchbase.com
Rockstar Developer () MongoDB (NoSQL Database) 261
Unstructured Data
Software Data
Software Data
User Desktop User Data
Mobile User Third-party Service
Data Service Data
Structure Data User Input Data
Error Log Traffic Statistics Usage Behavior User Location Data
Software Data
Data Schema
Rockstar Developer () MongoDB (NoSQL Database) 262
Source couchbase.com
()
Database Data Structure
Data Structure
Data
Data Structure
Data Structure
Key-Value Store,
Column Families Store,
Document Store
Graph Database
Redis
Redis
Performance
File System Memory
Cache App State Data
Traffic Statistic Data Usage Behavior Data
Source thoughtworks.com
Source thoughtworks.com
(.) BigCo
Node
Address, Product, Service Property Anna
Node Node Email, Position, Marital Status Property
Anna Node Employee Edge Edge
BigCo Employee Edge Employee Since
Relationship Unidirectional Relationship
Graph
Anna BigCo Employee
Edge
Martin Friend
Edge Pramod Pramod Friend Edge Martin
Node Relationship
11.3 MongoDB
MongoDB Document Store NoSQL Database Client-Server
Database Server Client Software
MongoDB Installer Version
mongodb.org Download Installer mongod, mongo, mongoexport,
mongoimport, mongodump, mongorestore Command Line Tool
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/
$ mongo
> help
local 0.078125GB
switched to db mydb
> db
mydb
local 0.078125GB
local 0.078125GB
mydb 0.203125GB
>
db Command Database db
Command Run mydb
Database db.dropDatabase()
> db.dropDatabase()
>
switched to db mydb
> db.createCollection("issues")
{ "ok" : 1 }
issues
system.indexes
>
Rockstar Developer () MongoDB (NoSQL Database) 271
issues
system.indexes
users
>
> db.users.drop()
true
issues
system.indexes
>
> db.issues.insert({
... subject: "Dropdown menu not working",
... priority: {
... value: 2,
... label: "Important"
... },
... severity: {
... value: 1,
... label: "Minor"
... },
Rockstar Developer () MongoDB (NoSQL Database) 272
... assignedTo: {
... name: "John Doe",
... userId: 1
... },
... status: {
... value: 1,
... label: "Assigned"
... }
... })
>
priority: 2
2 Label Priority Table JOIN
Relationship Priority 2 Label
Important Document
Array
> db.users.insert([
... { name: "John Doe", role: "Admin" },
... { name: "James Smith", role: "Tester" }
... ])
>
Document find()
> db.users.find()
>
4 bytes Timestamps
3 bytes Machine ID
2 bytes Process ID
3 bytes Auto-Increment Counter
> db.users.find()
> ObjectId("55350aea459cc324c59cf1aa").getTimestamp()
ISODate("2015-04-20T14:19:22Z")
> ObjectId("55350aea459cc324c59cf1aa").str
55350aea459cc324c59cf1aa
>
> db.users.find()
> db.users.save({
... _id : ObjectId("55350aea459cc324c59cf1aa"),
... name: "John Doe",
... role: "Developer"})
> db.users.find()
>
> db.users.find().pretty()
{
"_id" : ObjectId("55350aea459cc324c59cf1aa"),
"name" : "John Doe",
"role" : "Developer"
}
{
"_id" : ObjectId("55350aea459cc324c59cf1ab"),
"name" : "James Smith",
"role" : "Tester"
}
>
AND Query
OR Query
> db.issues.find({
... $or: [
... { "status.value": 1 },
... { "severity.value": 3 }
... ]
... });
>
> db.issue.find({
... "status.value": { $gt: 1 }
... })
>
>
> db.users.find().limit(2)
> db.users.find().skip(5).limit(10)
Query Document
> db.users.update(
... { role: "Developer" },
... { $set: { role: "Programmer" } }
... { multi: true }
... )
>
> db.issues.dropIndex("PrimaryKey")
> db.issues.dropIndex({ status: 1 })
Index dropIndexes()
Index getIndexes()
Rockstar Developer () MongoDB (NoSQL Database) 279
> db.issues.getIndexes()
Text Index
{
"queryDebugString" : "menu||||||",
"language" : "english",
"results" : [
{
"score" : 0.6666666666666666,
"obj" : {
"_id" : ObjectId("553508f5459cc324c59cf1a9"),
"subject" : "Dropdown menu not working",
"priority" : {
"value" : 2,
"label" : "Important"
},
"assignedTo" : {
"name" : "John Doe",
"id" : 1
},
"status" : {
"value" : 1,
"label" : "Assigned"
Rockstar Developer () MongoDB (NoSQL Database) 280
}
}
}
],
"stats" : {
"nscanned" : 1,
"nscannedObjects" : 0,
"n" : 1,
"nfound" : 1,
"timeMicros" : 197
},
"ok" : 1
}
>
switched to db admin
{
"user" : "root",
"readOnly" : false,
"pwd" : "2a8025f0885adad5a8ce0044070032b3",
"_id" : ObjectId("5536899f1d331f653a28893e")
}
>
Rockstar Developer () MongoDB (NoSQL Database) 281
switched to db admin
>
Username, Password
db.auth() Function Authenticate
system.indexes
system.users
switched to db mydb
{
"user" : "user",
"readOnly" : false,
"pwd" : "fa26a506aa0f786a447bbd6d1caaa8b5",
"_id" : ObjectId("55368c6c3e0d2164a31a2ec8")
}
>
switched to db admin
>
{
"user" : "user",
"readOnly" : 1,
"pwd" : "fa26a506aa0f786a447bbd6d1caaa8b5",
"_id" : ObjectId("55368d46d3bc6702df267302")
}
>
Readonly User
Rockstar Developer () MongoDB (NoSQL Database) 283
switched to db mydb
issues
system.indexes
system.users
users
> db.createCollection('comments')
>
Access Control
MongoDB Version 2.4 MongoDB
Version 2.6 Access Control addUser()
Function User Account Role
createUser() Function Access Control
http://docs.mongodb.org/manual/tutorial/add-user-to-database/
mongodump Backup
Restore mongorestore
Backup Directory Run
Director Run Backup Access Control
-o Option export.json
-o Option Terminal Output CSV
Format
--csv Option Export
Export
Field List -f Option Access
Control Username, Password -u, -p Option
mongoexport
Backup Restore
mongoimport
http://docs.mongodb.org/ecosystem/tools/administration-interfaces/
Robomongo
Admin Tool
Robomongo Windows, Linux, Mac Platform Tool
robomongo.org Installer Download
Collection Document
Document Tree View, Table View, Document View View
Toolbar Button View
Shell Robomongo
NPM Package
Mongo Shell
mongojs Official Driver mongojs
mongojs Install
JavaScript
JavaScript
JavaScript
JavaScript
1. db.users.insert({
2. name: "Ei Maung",
3. role: "Developer"
4. }, function() {
5. db.close();
6. });
Document
JavaScript
1. db.users.remove({
2. _id: mongojs.ObjectId("5537b76a292e04f67d2af4c1")
3. }, function() {
4. db.close();
5. });
JavaScript
1. db.users.update(
2. { role: "Admin" },
3. { $set: { role: "Developer" } },
4. { multi: true },
5. function() {
6. db.close();
7. }
8. );
JavaScript
Text Index
JavaScript
Conclusion
RDBMS NoSQL Database
RDBMS ACID Compliance
NoSQL Not Only SQL
RDBMS RDBMS
Software
RDBMS NoSQL Database
RDBMS Cache
Real-time Data, State Data Unstructured Data NoSQL Database
Opinionated Framework
Framework
Unopinionated Framework
http://pwdbook.com
Rockstar Developer () ExpressJS (REST Framework) 294
Code Code
JavaScript
$ node server.js
JavaScript
URI Request
index.html Response
/about URI Request
about.html Response
__dirname Constant Directory Absolute Path
Code
JavaScript
16. });
17. });
Ejs
() BackboneJS
Underscore Template JavaScript Code HTML
<% %> Tag Output
<%= %> Tag
about.html
Template
<h1>About Us</h1>
<p><%= greeting %></p>
HTML
<h1>About Us</h1>
<p>Hello, World!</p>
12.1 Routing
REST API Web Service
HTTP Request Method URL
ExpressJS Routing
Function
ExpressJS
URL Structure
JavaScript
JavaScript
JavaScript
JavaScript
app.route("users/")
.get(function(req, res) {
console.log("Getting user list");
})
.delete(function(req, res) {
console.log("Removing all users");
});
JavaScript
user-router.js
JavaScript
Home Sub App Route Pattern User Sub App Route Pattern
App Router Sub App
JavaScript
JavaScript
Static Server
Sub App ()
JavaScript
app.use('/static', express.static('static'));
ExpressJS /static
URL Static Server
JavaScript
body-parser Install
body-parser req.body
Property Form Data JSON Object
JavaScript
JavaScript
() multer Module
Request Directory Location
JavaScript
JSON
{
"name": {
"fieldname": "file",
"originalname": "express.js",
"name": "4f4ac9f6ed1ba0e8515f6144a6efb183.js",
"encoding": "7bit",
"mimetype": "application/javascript",
"path": "upload/4f4ac9f6ed1ba0e8515f6144a6efb183.js",
"extension": "js",
"size": 471,
"truncated": false,
"buffer": null
}
}
Rockstar Developer () ExpressJS (REST Framework) 305
Code
JavaScript
cookie-parser app.use() ()
ExpressJS Request Cookie Data
req.cookies JSON Object
Session Code
JavaScript
https://github.com/expressjs/session
Request Property
req.ip
req.xhr ExpressJS req.ip Property Request Client IP
Address Request Ajax Request req.xhr
true
JavaScript
res.status(200).send("Response Body");
res.status(404).sendFile("/path/to/not-found.png");
JavaScript
JavaScript
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123'
});
JavaScript
res.append('Content-Encoding', 'gzip');
JavaScript
res.attachment('path/to/logo.png');
JavaScript
JavaScript
JavaScript
res.clearCookie("foo");
Redirect URL
Redirect res.redirect()
JavaScript
/about URL
Request /home/about-us
Redirect
Directory Structure
Rockstar Developer () ExpressJS (REST Framework) 310
myApp
node_modules
body-parser
express
mongojs
static
about.html
contact.html
index.html
api.js
index.js
JavaScript
Request Handler ()
index.js
JavaScript
() api.js require()
() App static Directory
() api.js /api Sub App
App
Request
Rockstar Developer () ExpressJS (REST Framework) 312
http://curl.haxx.se/download.html
[{"_id":"553b7f726ab0b99f0664b180","name":"Jonh Doe","role":"Developer"},
{"_id":"553b7f7f6ab0b99f0664b181","name":"Jame Smith","role":"Tester"}]
"553bd0d215349a0864c5df60"
[{"_id":"553b7f726ab0b99f0664b180","name":"Jonh Doe","role":"Developer"},
{"_id":"553b7f7f6ab0b99f0664b181","name":"Jame Smith","role":"Tester"},
{"name":"Bob","role":"Tester","_id":"553bd0d215349a0864c5df60"}]
Rockstar Developer () ExpressJS (REST Framework) 314
GET /api/users/:id
[{"name":"Bob","role":"Tester","_id":"553bd0d215349a0864c5df60"}]
[{"name":"Alice","role":"Tester","_id":"553bd0d215349a0864c5df60"}]
[{"_id":"553b7f726ab0b99f0664b180","name":"Jonh Doe","role":"Developer"},
{"_id":"553b7f7f6ab0b99f0664b181","name":"Jame Smith","role":"Tester"}]
$ express myApp
create : myApp
create : myApp/package.json
create : myApp/myApp.js
install dependencies:
$ cd myApp && npm install
myApp
bin
www
node_modules
body-parser
cookie-parser
debug
express
jade
morgan
serve-favicon
public
images
javascripts
stylesheets
style.css
routes
index.js
users.js
views
error.jade
index.jade
layout.jade
app.js
package.json
$ express -e myApp
Conclusion
Web Application Development Development Stack
LAMP Stack Linux OS, Apache Web Server, MySQL Database, PHP
Development Environment
Professional Web Developer Ubuntu Linux LAMP Stack
Covered
JavaScript
MEAN Development Stack LAMP Stack
MEAN
MongoDB, ExpressJS, AngularJS NodeJS
Develop-ment Stack
() MEAN Stack
AngularJS BackboneJS
MEAN Stack Modern Development Stack
BackboneJS, NodeJS, MongoDB ExpressJS JavaScript
Development Stack
()
Authentication
Proven Component
Ubuntu Linux ()
Ubuntu Linux Installation System
Configuration Development Environment
http://u4ubook.com
Rockstar Developer () Building Back-end Service 319
Code
Code
Code
Code
Download
https://github.com/eimg/issues-api/archive/master.zip
13.1 Scaffolding
issues-api
(
) Directory
Directory Package NPM Install
issues-api
node_modules
body-parser
cookie-parser
express
express-session
express-validator
mongojs
passport
passport-local
Structure
issues-api
app.js
auth.js
config.js
node_modules
routes
issues.js
users.js
JavaScript
1. exports.role = [
2. "User",
3. "Tester",
4. "Developer",
5. "Manager"
6. ];
7.
8. exports.status = [
9. "New",
10. "Assigned",
11. "Doing",
12. "Done",
13. "Closed"
14. ];
15.
16. exports.type = [
17. "Bug",
18. "Feature",
19. "Other"
20. ];
21.
22. exports.priority = [
23. "Low",
24. "High",
25. "Urgent"
26. ];
JavaScript
8. passport.serializeUser(function(user, done) {
9. done(null, user);
10. });
11.
12. passport.deserializeUser(function(user, done) {
13. done(null, user);
14. });
15.
16. // Authentication strategy
17. passport.use(new LocalStrategy(
18. function(username, password, done) {
19. var pwdHash = crypto.createHash('sha1').update(password).digest("hex");
20.
21. db.users.findOne({
22. loginId: username,
23. password: pwdHash
24. }, function(err, data) {
25. if(data)
26. return done(null, data);
27. else
28. return done(null, false);
29. });
30. }
31. ));
32.
33. exports.login = function() {
34. return passport.authenticate("local");
35. }
36.
37. exports.ensureAuth = function() {
38. return function(req, res, next) {
39. if(req.isAuthenticated())
40. next()
41. else res.sendStatus(401);
42. }
43. }
JavaScript
() passport.serializeUser() Function
Function JSON User Data Session Text
() passport.deserializeUser() Session
User Data JSON
User Data JSON Session Text
Function Serialize Deserialize
Callback Function
Serialize/Deserialize
done() Function
Authorization () ensureAuth()
Function
Request Login Access Function
Login Session User Data
PassportJS
req.isAuthenticated() Function Authenticated User
Authenticated User
Next Route
next() Function Authenticated User 401 Status Code
Authentication Authorization
User
Role Authorization auth.js
JavaScript
68. else
69. res.sendStatus(401);
70. }
71. };
72.
73. exports.ensureAssignee = function() {
74. return function(req, res, next) {
75. var iid = req.params.id;
76. db.issues.findOne({ _id: mongojs.ObjectId(iid) }, function(err,data){
77. if(err) {
78. res.sendStatus(401);
79. } else {
80. if (req.isAuthenticated() &&
81. (req.user._id.str==(data.assignedTo && data.assignedTo.str) ||
82. req.user.role === 3))
83. next();
84. else
85. res.sendStatus(401);
86. }
87. });
88. }
89. };
90.
91. exports.ensureSubmitter = function() {
92. return function(req, res, next) {
93. var iid = req.params.id;
94. db.issues.findOne({ _id: mongojs.ObjectId(iid) }, function(err,data){
95. if(err) {
96. res.sendStatus(401);
97. } else {
98. if (req.isAuthenticated() && (req.user._id == data.submittedBy ||
99. req.user.role === 3))
100. next();
101. else
102. res.sendStatus(401);
103. }
104. });
105. }
106. };
() ensureAssignee() Function
Issue Status Manager Assign
User Status
Issue Assigned To
Authenticated User ID Assign User
Issue Assigned To Database
Database
() ensureSubmitter() ensureAssignee()
Issue
Authorization Authentication
JavaScript
() express-validator
Request Data Validate Package
() () config.js auth.js
.js Extension .js Extension
Login
() /login URI POST Route
auth.js login() Function
auth.login() Route Function auth.login()
Username, Password Session User Data
Route Function req.user 200 Status Code
User Data Response 401 Response
User
JavaScript
User
() () Validation express-validator
req.checkBody() Function Request Body Validate
req.checkBody()
checkBody() Function Field Error Message
Rockstar Developer () Building Back-end Service 330
express-validator
() req.validation
Errors() Function Error Error 400 Status Code Error
Message Response
JavaScript
73. }
74.
75. db.users.findOne({_id: mongojs.ObjectId(uid)}, function(err, data) {
76. if(data) res.status(200).json(data);
77. else res.sendStatus(404);
78. });
79. });
80.
81. // Update a user
82. router.put("/:id", auth.ensureOwner(), function(req, res) {
83. var uid = req.params.id;
84.
85. // Validation
86. req.checkParams("id", "Invalid User ID").isMongoId();
87. req.checkBody('fullName', 'Invalid Full Name').isLength(3);
88. req.checkBody('loginId', 'Invalid Login ID').isAlphanumeric();
89. req.checkBody('email', 'Invalid Email Address').isEmail();
90. req.checkBody('role', 'Invalid Role').isInt();
91.
92. var errors = req.validationErrors();
93. if(errors) {
94. res.status(400).json(errors);
95. return false;
96. }
97.
98. var newData = {
99. fullName: req.body.fullName,
100. loginId: req.body.loginId,
101. email: req.body.email,
102. role: req.body.role,
103. roleLabel: config.role[req.body.role]
104. };
105.
106. if(req.body.password) {
107. var pwdHash = crypto.createHash('sha1')
108. .update(req.body.password)
109. .digest("hex");
110. newData.password = pwdHash;
111. }
112.
113. db.users.update(
114. { _id: mongojs.ObjectId(uid) },
115. { $set: newData },
116. { multi: false },
117. function(err, data) {
118. if(err) res.status(500).json(err);
119. else res.status(200).json(data);
120. }
121. );
123. });
124.
125. router.delete("/:id", auth.ensureSuper(), function(req, res) {
126. var uid = req.params.id;
127.
128. // Validation
129. req.checkParams("id", "Invalid User ID").isMongoId();
130. var errors = req.validationErrors();
131. if(errors) {
132. res.status(400).json(errors);
Rockstar Developer () Building Back-end Service 332
Route Pattern
JavaScript
JavaScript
276. });
Issue Comment
JavaScript
277. // Comments
278. router.post("/comments", auth.ensureAuth(), function(req, res) {
279. req.checkBody('issueId', 'Invalid Issue ID').isMongoId();
280. req.checkBody('authorId', 'Invalid Author ID').isMongoId();
281. req.checkBody('authorName', 'Invalid Author Name').notEmpty();
282. req.checkBody('comment', 'Invalid Comment Body').notEmpty();
283.
284. var errors = req.validationErrors();
285. if(errors) {
286. res.status(400).json(errors);
287. return false;
288. }
289.
290. db.issues.findOne({
291. _id: mongojs.ObjectId(req.body.issueId)
292. }, function(err, data) {
293. if(data) {
294. var comments = data.comments || [];
295. var comment = {
296. comment: req.body.comment,
297. authorId: req.body.authorId,
298. authorName: req.body.authorName,
299. submittedAt: new Date()
300. }
301.
302. comments.push(comment);
303.
304. db.issues.update(
305. { _id: mongojs.ObjectId(req.body.issueId) },
306. { $set: { comments: comments } },
307. { multi: false },
308. function(err, data) {
309. if(err) res.status(500).json(err);
310. else res.status(200).json(data);
311. }
312. );
Rockstar Developer () Building Back-end Service 339
313. }
314. else {
315. res.sendStatus(404);
316. }
317. });
318. });
319.
320. router.delete("/comments", auth.ensureAuth(), function(req, res) {
321. req.checkBody('issueId', 'Invalid Issue ID').isMongoId();
322. req.checkBody('commentId', 'Invalid Comment ID').isInt();
323.
324. var errors = req.validationErrors();
325. if(errors) {
326. res.status(400).json(errors);
327. return false;
328. }
329.
330. db.issues.findOne({
331. _id: mongojs.ObjectId(req.body.issueId)
332. }, function(err, data) {
333. if(data) {
334. var comments = data.comments || [];
335. comments.splice(req.body.commentId, 1);;
336.
337. db.issues.update(
338. { _id: mongojs.ObjectId(req.body.issueId) },
339. { $set: { comments: comments } },
340. { multi: false },
341. function(err, data) {
342. if(err) res.status(500).json(err);
343. else res.status(200).json(data);
344. }
345. );
346. }
347. else {
348. res.sendStatus(404);
349. }
350. });
351. });
Issue Router
Issue Status, Priority Type Route
Rockstar Developer () Building Back-end Service 340
JavaScript
Route Pattern
Main App
JavaScript
require() app.use()
Package
() Static File Server
Static Response ./static
Directory () ()
Issue Router User Router Sub-App
/api/issues /api/users API URL
() Access-Control-Allow-Origin http://localhost:8080
Server localhost:8080 Cross-Origin Request
Web Client example.com
http://example.com Client
Cross-Origin Request *
JavaScript
res.set("Access-Control-Allow-Origin", "*");
() Access-Control-Allow-Credentials true
Cross-Origin Request Cookie
Header
Cross-Origin Request Cookie
Code Access-Control-Allow-Origin
* http://localhost:8080
Access-Control-Allow-Credentials true Access-Control-Allow-Origin *
CORS
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
$ node
> var crypto = require("crypto");
> var password =
crypto.createHash("sha1").update("123456").digest("hex");
> console.log(password);
7c4a8d09ca3762af61e59520943dc26494f8941b
123456
SHA1 Hash Generate
Mongo Shell Manager Account
Rockstar Developer () Building Back-end Service 344
$ mongo
> use mydb;
switched to db mydb
> db.users.insert({
... fullName: "John Doe",
... loginId: "manager",
... email: "john@example.com",
... role: 3,
... password: "7c4a8d09ca3762af61e59520943dc26494f8941b"
... });
> db.users.find().pretty();
{
"_id" : ObjectId("55b703a9d2141ae9733ac0eb"),
"fullName" : "John Doe",
"loginId" : "manager",
"email" : "john@example.com",
"role" : 3,
"password" : "7c4a8d09ca3762af61e59520943dc26494f8941b"
}
$ node app.js
Service Port 3000 CURL
Verify
Unauthorized%
{"_id":"55b70503d2141ae9733ac0ec","fullName":"John
Doe","loginId":"manager","email":"john@example.com","role":3,"password":"7c4a8
d09ca3762af61e59520943dc26494f8941b"}%
Unauthorized%
{"_id":"55b70503d2141ae9733ac0ec","fullName":"John
Doe","loginId":"manager","email":"john@example.com","role":3,"password":"7c4a8
d09ca3762af61e59520943dc26494f8941b"}%
{"_id":"55b70503d2141ae9733ac0ec","fullName":"John
Doe","loginId":"manager","email":"john@example.com","role":3,"password":"7c4a8
d09ca3762af61e59520943dc26494f8941b"}%
User
Rockstar Developer () Building Back-end Service 346
[{"_id":"55b70503d2141ae9733ac0ec","fullName":"John
Doe","loginId":"manager","email":"john@example.com","role":3,"password":"7c4a8
d09ca3762af61e59520943dc26494f8941b"}]%
User
{"fullName":"Bob","loginId":"bob","email":"bob@gmail.com","role":"2","password
":"7c4a8d09ca3762af61e59520943dc26494f8941b","roleLabel":"Developer","_id":"55
b70b342468830b671da93b"}%
User
Response
{"fullName":"Bob","loginId":"bob","email":"bob@gmail.com","role":"2","password
":"7c4a8d09ca3762af61e59520943dc26494f8941b","roleLabel":"Developer","_id":"55
b70b342468830b671da93b"}%
Rockstar Developer () Building Back-end Service 347
[{"_id":"55b70503d2141ae9733ac0ec","fullName":"John
Doe","loginId":"manager","email":"john@example.com","role":3,"password":"7c4a8
d09ca3762af61e59520943dc26494f8941b"},
{"fullName":"Bob","loginId":"bob","email":"bob@gmail.com","role":"2","password
":"7c4a8d09ca3762af61e59520943dc26494f8941b","roleLabel":"Developer","_id":"55
b70b342468830b671da93b"}]%
Unauthorized%
Code
https://github.com/eimg/issues-api/archive/master.zip
Conclusion
REST API HTTP Request Method HTTP Status Code
Back-end Service URL
Routing Session Based Authentication
Compression Cache
Response Plain Text Compress
Response Cache Content Cache Cache
Content Cache Cache-Control Header Response
Back-end Service
API Version
Service Client
Service
Client
Rockstar Developer () Building Back-end Service 348
Service
Client
Request
Server Resource Client
Client
Request Client Request
http://eimaung.com/courses
Rockstar Developer () Building Clients (HTML Templates) 350
14.1 Bootstrap 3
Bootstrap CSS Framework Device Screen Size
Layout Responsive Layout
CSS Style JavaScript Component Framework
Version Version 3.2.0
Layout
Bootstrap Layout Bootstrap Column
() Layout Layout Structure
HTML
1. <div class="container">
2. <div class="row">
3. <div class="col-md-12"></div>
4. </div>
5. <div class="row">
6. <div class="col-md-4"></div>
7. <div class="col-md-8"></div>
8. </div>
9. </div>
Rockstar Developer () Building Clients (HTML Templates) 351
.row Column
Layout
Row Size () Column Row
() Column ()
Column
Column Layout
Column Size Layout
HTML
1. <div class="container">
2. <div class="row">
3. <div class="col-md-12"></div>
4. </div>
5. <div class="row">
6. <div class="col-md-8 col-sm-6 col-xs-12"></div>
7. <div class="col-md-4 col-sm-6 col-xs-12"></div>
8. </div>
9. </div>
Styles
Bootstrap Basic Element h1-h6, p, a Element
Default
Style Element Bootstrap Style
Class Table Element Bootstrap Style
.table Class
HTML
1. <table class="table">
2. <tr>
3. <th> </th>
4. <th> </th>
5. </tr>
6. <tr>
7. <td> </td>
8. <td> </td>
9. </tr>
10. </table>
Rockstar Developer () Building Clients (HTML Templates) 353
HTML
HTML
1. <div class="form-group">
2. <label for="email">Email address</label>
3. <input type="email" class="form-control" id="email">
4. </div>
HTML
<span class="caret"></span>
Components
Bootstrap Component Icon Icon
Image Bootstrap Icon
Button Add Icon
HTML
HTML
1. <div class="dropdown">
2. <button class="btn btn-default" data-toggle="dropdown">
3. Dropdown <span class="caret"></span>
4. </button>
5. <ul class="dropdown-menu">
6. <li> ... </li>
7. <li> ... </li>
8. </ul>
9. </div>
HTML
HTML
HTML
HTML
HTML
JavaScript
$("table").dataTables();
Sorting Sorting
() DataTables
Issue Status New, Assigned, Doing, Done,
Close Sorting Assigned, Close,
Doing, Done, New A-Z
New (0),
Assigned (1), Doing (2)
DataTables order-value
Attribute
Rockstar Developer () Building Clients (HTML Templates) 360
HTML
1. <table>
2. <tr><td order-value="1">Assigned</td></tr>
3. <tr><td order-value="4">Close</td></tr>
4. <tr><td order-value="0">New</td></tr>
5. <tr><td order-value="3">Done</td></tr>
6. <tr><td order-value="2">Doing</td></tr>
7. </table>
Device
Responsive Table Design
DataTables Bootstrap Library Style
DataTables Bootstrap Table Style Screen
Size
DataTables Bootstrap 3 Plugin DataTables Responsive
Plugin
Code
Code
Code
Download
https://github.com/eimg/issues-backbone/archive/master.zip
Directory Structure
issues-backbone
bower_components
backbone
bootstrap
bootstrap3-wysiwyg
datatables
datatables-bootstrap3
datatables-responsive
Rockstar Developer () Building Clients (HTML Templates) 362
jquery
jquery-validate
moment
underscore
issues-backbone
app.js
index.html
issues.js
users.js
bower_components
templates
issue-detail.html
issue-edit.html
issue.html
issue-list.html
issue-new.html
login.html
nav.html
user-edit.html
user.html
user-list.html
user-new.html
user-profile.html
views
appView.js
issueDetailView.js
issueEditView.js
issueListView.js
issueNewView.js
loginView.js
navView.js
userEditView.js
userListView.js
userNewView.js
userProfileView.js
Template
1. <div class="row">
2. <div class="col-md-8 col-sm-12 col-xs-12">
3. <div class="panel
4. <% if(priority == 0) { %>
5. panel-info
6. <% } else if (priority == 1) { %>
7. panel-warning
8. <% } else { %>
9. panel-danger
10. <% } %>
11. issue-detail">
12. <div class="panel-heading">
13. <h2>
14. <% if(type == 0) { %>
15. <span class="glyphicon glyphicon-fire"></span>
16. <% } else if (type == 1) { %>
17. <span class="glyphicon glyphicon-heart-empty"></span>
18. <% } else { %>
19. <span class="glyphicon glyphicon-asterisk"></span>
20. <% } %>
21. <%= summary %>
22. <span class="pull-right small">#<%= _id %></span>
23. </h2>
24. </div>
25. <div class="panel-body">
26. <%= detail %>
27. </div>
28. <div class="panel-footer clearfix">
29. <span class="text-muted"><%= moment(submittedAt).fromNow() %></span>
30. <div class="btn-group pull-right">
31. <button class="btn btn-default btn-sm" id="close-issue">
32. <span class="glyphicon glyphicon-ok text-success"></span>
33. Close
34. </button>
35. <button class="btn btn-default btn-sm" id="edit-issue">
36. <span class="glyphicon glyphicon-edit text-info"></span>
37. Edit
38. </button>
39. <button class="btn btn-default btn-sm" id="delete-issue">
40. <span class="glyphicon glyphicon-trash text-danger"></span>
41. Remove
42. </button>
43. </div>
44. </div>
45. </div>
46.
47. <hr>
48. <% if(typeof comments !== "undefined") { %>
49. <% _.each(comments, function(comment, id) { %>
50.
51. <div class="panel panel-default small comment">
Rockstar Developer () Building Clients (HTML Templates) 364
Template
21. </button>
22. <button class="btn btn-link" id="close-edit">Cancel</button>
23. </form>
24.
25. <script>
26. $(function() {
27. $('.editor').wysihtml5({
28. toolbar: {
29. "font-styles": false,
30. "emphasis": true,
31. "lists": true,
32. "html": false,
33. "link": true,
34. "image": false,
35. "color": false,
36. "blockquote": false,
37. "size": "sm"
38. }
39. });
40. });
41. </script>
View
Template
1. <table id="issue-list-table"
2. class="table table-bordered" cellspacing="0" width="100%">
3. <thead>
4. <tr>
5. <th>#</th>
6. <th width="50%">Summary</th>
7. <th>Type</th>
8. <th>Assigned To</th>
9. <th>Priority</th>
10. <th>Status</th>
11. </tr>
12. </thead>
13.
14. <tbody>
15.
16. </tbody>
17. </table>
18.
19. <script>
20. $(function() {
21. $("#issue-list-table").dataTable({
22. responsive: true
23. });
24. });
25. </script>
Template
Template
53. });
54. </script>
Template
Template
1. <div class="container-fluid">
2. <div class="navbar-header">
3. <button type="button" class="navbar-toggle"
4. data-toggle="collapse" data-target=".navbar-collapse">
5. <span class="icon-bar"></span>
6. <span class="icon-bar"></span>
7. <span class="icon-bar"></span>
8. </button>
9. <a class="navbar-brand" href="#">Issue Tracking System</a>
10. </div>
11. <div class="navbar-collapse collapse">
12. <% if(auth) { %>
13. <ul class="nav navbar-nav">
14. <li class="active">
15. <a href="#/issues" id="issue-list">
16. All Issues <span class="badge"><%= issueCount %></span>
17. </a>
18. </li>
19. <li><a href="#" id="my-issues">My Issues <span class="badge">
20. <%= myIssues %></span></a></li>
21. <li>
22. <a href="#" id="new-issue">
23. <span class="text-primary glyphicon glyphicon-plus"></span>
24. New Issue
25. </a>
26. </li>
27. </ul>
28. <ul class="nav navbar-nav navbar-right">
29. <li><a href="#/users" id="user-list">Users</a></li>
30. <li><a href="#" id="profile"><%= userName %></a></li>
31. <li><a href="#" id="logout">Logout</a></li>
32. </ul>
33. <% } %>
34. </div>
35. </div>
Template
1. <h2>Edit User</h2>
2.
3. <form action="#" id="edit-user-form">
4. <div class="form-group">
5. <label for="">Full Name *</label>
6. <input type="text" class="form-control"
7. placeholder="Full Name" id="full-name" value="<%= fullName %>">
8. </div>
9. <div class="form-group">
10. <label for="">Login ID *</label>
11. <input type="text" class="form-control"
12. placeholder="Login ID" id="login-id" value="<%= loginId %>">
13. <span class="help-block">No space, small letters</span>
14. </div>
15. <div class="form-group" placeholder="Email">
16. <label for="">Email *</label>
17. <input type="email" class="form-control" id="email"
18. placeholder="Email" value="<%= email %>">
19. </div>
20. <div class="form-group">
21. <label for="">Role *</label>
22. <select class="form-control" id="role">
23. <% _.each(app.userRole, function(name, value) { %>
24. <option value="<%= value %>"
25. <%= value == role ? 'selected' : '' %>><%= name %></option>
26. <% }) %>
27. </select>
28. </div>
29. <div class="form-group">
30. <label for="">Password (twice)</label>
31. <div class="row">
32. <div class="col-md-6">
33. <input type="password" class="form-control"
34. placeholder="Password" id="password">
35. <span class="help-block">Leave blank if you don't
36. want to change password</span>
37. </div>
38. <div class="col-md-6">
39. <input type="password" class="form-control"
40. placeholder="Password Again" id="password-again">
Rockstar Developer () Building Clients (HTML Templates) 375
41. </div>
42. </div>
43. </div>
44.
45. <button type="submit" class="btn btn-primary btn-lg" id="update-user">
46. <span class="glyphicon glyphicon-check"></span>
47. Update User
48. </button>
49. </form>
User Full Name, Login ID, Email, Role Password Form Template
Template
1. <div class="table-responsive">
2. <table id="issue-list" class="table table-bordered"
3. cellspacing="0" width="100%">
4. <thead>
5. <tr>
6. <th>#</th>
7. <th>Full Name</th>
8. <th>Login ID</th>
9. <th>Email</th>
10. <th>Role</th>
11. <th width="160">Manage</th>
12. </tr>
13. </thead>
14.
15. <tbody>
16.
17. </tbody>
18. </table>
19. </div>
20.
21. <button class="btn btn-primary" id="new-user">
22. <span class="glyphicon glyphicon-plus-sign"></span>
23. New User
24. </button>
Table
templates/
user.html
Rockstar Developer () Building Clients (HTML Templates) 376
Template
Template
1. <h2>New User</h2>
2.
3. <form action="#" id="new-user-form">
4. <div class="form-group">
5. <label for="">Full Name *</label>
6. <input type="text" class="form-control"
7. placeholder="Full Name" id="full-name">
8. </div>
9. <div class="form-group">
10. <label for="">Login ID *</label>
11. <input type="text" class="form-control"
12. placeholder="Login ID" id="login-id">
13. <span class="help-block">No space, small letters</span>
14. </div>
15. <div class="form-group" placeholder="Email">
16. <label for="">Email *</label>
17. <input type="email" class="form-control" id="email"
18. placeholder="Email">
19. </div>
20. <div class="form-group">
21. <label for="">Role *</label>
22. <select class="form-control" id="role">
23. <% _.each(app.userRole, function(name, value) { %>
24. <option value="<%= value %>"><%= name %></option>
25. <% }) %>
26. </select>
Rockstar Developer () Building Clients (HTML Templates) 377
27. </div>
28. <div class="form-group">
29. <label for="">Password (twice) *</label>
30. <div class="row">
31. <div class="col-md-6">
32. <input type="password" class="form-control"
33. placeholder="Password" id="password">
34. </div>
35. <div class="col-md-6">
36. <input type="password" class="form-control"
37. placeholder="Password Again" id="password-again">
38. </div>
39. </div>
40. </div>
41.
42. <button type="submit" class="btn btn-primary btn-lg" id="add-user">
43. <span class="glyphicon glyphicon-plus-sign"></span>
44. Add User
45. </button>
46. </form>
User Edit Full Name, Login ID, Email, Role Password Form Template
Template
1. <div class="row">
2. <div class="col-md-8 col-sm-12 col-xs-12">
3. <div class="panel panel-info issue-detail">
4. <div class="panel-heading">
5. <h2><span class="glyphicon glyphicon-user"></span>
6. <%= fullName %></h2>
7. </div>
8. <div class="panel-body">
9. <div class="form-horizontal" role="form">
10. <div class="form-group">
11. <label class="col-sm-2 control-label">Login ID</label>
12. <div class="col-sm-10">
13. <p class="form-control-static"><%= loginId %></p>
14. </div>
15. </div>
16. <div class="form-group">
17. <label class="col-sm-2 control-label">Email</label>
18. <div class="col-sm-10">
19. <p class="form-control-static"><%= email %></p>
20. </div>
21. </div>
Rockstar Developer () Building Clients (HTML Templates) 378
22. </div>
23. </div>
24. <div class="panel-footer clearfix">
25. <div class="btn-group pull-right">
26. <button class="btn btn-default btn-sm" id="edit-user">
27. <span class="glyphicon glyphicon-edit text-info"></span>
28. Edit
29. </button>
30. </div>
31. </div>
32. </div>
33. </div>
34.
35. <div class="col-md-4 col-sm-12 col-xs-12 sidebar">
36. <div class="btn-group btn-breadcrumb">
37. <a href="#" class="btn btn-info">
38. <span class="glyphicon glyphicon-star"></span></a>
39. <a href="#" class="btn btn-info">Role</a>
40.
41. <a href="#" class="btn btn-default"><%= roleLabel %></a>
42. <span></span>
43. </div>
44.
45. <div class="btn-group btn-breadcrumb">
46. <a href="#" class="btn btn-warning">
47. <span class="glyphicon glyphicon-plus-sign"></span></a>
48. <a href="#" class="btn btn-warning">Issue Submitted</a>
49.
50. <a href="#" class="btn btn-default">
51. <%= submitCount %>
52. </a>
53. <span></span>
54. </div>
55.
56. <div class="btn-group btn-breadcrumb">
57. <a href="#" class="btn btn-danger">
58. <span class="glyphicon glyphicon-tasks"></span></a>
59. <a href="#" class="btn btn-danger">Issue Assigned</a>
60.
61. <a href="#" class="btn btn-default">
62. <%= assignCount %>
63. </a>
64. <span></span>
65. </div>
66. </div>
67. </div>
() Code Structure
Code
http://eimaung.com/courses
Rockstar Developer () Building Clients (Web App) 381
Code Code
Code
Download
https://github.com/eimg/issues- backbone/archive/master.zip
JavaScript
1. var app = {
2. host: "http://localhost:3000/api",
3.
4. api: function(path) {
5. return app.host + path;
6. },
7.
8. templateCache: {},
9.
10. loadTemplates: function(names, callback) {
11. var that = this;
12. var load = function(index) {
13. var name = names[index];
14. console.log('Loading template: ' + name);
15. $.get('templates/' + name + '.html?cache=false', function(data) {
16. that.templateCache[name] = data;
17. index++;
18. if (index < names.length) {
19. load(index);
20. } else {
21. callback();
22. }
23. });
24. }
25.
26. load(0);
Rockstar Developer () Building Clients (Web App) 382
27. },
28.
29. hookTemplate: function(name, data) {
30. var tmpl = _.template(this.templateCache[name]);
31. return tmpl(data);
32. },
33.
34. login: function(user, pass, ok, notok) {
35. $.ajax({
36. type: "post",
37. url: this.api("/users/login"),
38. data: {
39. username: user,
40. password: pass
41. },
42. statusCode: {
43. 400: notok,
44. 401: notok,
45. 200: ok
46. }
47. });
48. },
49.
50. logout: function(callback) {
51. $.ajax({
52. type: "delete",
53. url: this.api("/users/logout"),
54. complete: callback
55. });
56.
57. localStorage.removeItem("user");
58. },
59.
60. verify: function(ok, notok) {
61. $.ajax({
62. url: this.api("/users/verify"),
63. statusCode: {
64. 401: notok,
65. 200: ok
66. }
67. });
68. },
69.
70. saveUserInfo: function(user) {
71. localStorage.setItem("user", JSON.stringify(user));
72. },
73.
74. getUserInfo: function() {
75. return JSON.parse(localStorage.getItem("user"));
76. },
77.
78. issueType: [],
79. issuePriority: [],
80. issueStatus: [],
81. userRole: [],
82.
83. loadIssueTypes: function() {
84. var that = this;
Rockstar Developer () Building Clients (Web App) 383
85. $.ajax({
86. url: this.api("/issues/types"),
87. success: function(data) {
88. that.issueType = data;
89. }
90. });
91. },
92.
93. loadIssuePriorities: function() {
94. var that = this;
95. $.ajax({
96. url: this.api("/issues/priorities"),
97. success: function(data) {
98. that.issuePriority = data;
99. }
100. });
101. },
102.
103. loadIssueStatuses: function() {
104. var that = this;
105. $.ajax({
106. url: this.api("/issues/statuses"),
107. success: function(data) {
108. that.issueStatus = data;
109. }
110. });
111. },
112.
113. loadUserRoles: function() {
114. var that = this;
115. $.ajax({
116. url: this.api("/users/roles"),
117. success: function(data) {
118. that.userRole = data;
119. }
120. });
121. },
123.
124. init: function() {
125. this.loadTemplates(['nav', 'login', 'issue-list',
126. 'issue', 'issue-new', 'issue-detail', 'issue-edit',
127. 'user-list', 'user', 'user-profile', 'user-edit', 'user-new'
128. ], function() {
129. new appView();
130. });
131. }
132. }
133.
134. $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
135. options.crossDomain = {
136. crossDomain: true
137. };
138.
139. options.xhrFields = {
140. withCredentials: true
141. };
142. });
Rockstar Developer () Building Clients (Web App) 384
() loadIssueTypes(), loadIssuePriorities(),
loadIssueStatuses() loadUserRoles() Function
Function API Server Request Issue Types, Priorities,
Statuses User Roles Property
JavaScript
1. app.issueModel = Backbone.Model.extend({
2. urlRoot: app.api("/issues"),
3. defaults: {
4. "assignedTo" : null,
5. "detail" : null,
6. "priority" : 0,
7. "priorityLabel" : "Low",
8. "status" : 0,
9. "statusLabel" : "New",
10. "summary" : null,
11. "type" : 0,
12. "typeLabel" : "Bug"
13. },
14.
15. idAttribute: "_id"
16. });
17.
18. app.issueCollection = Backbone.Collection.extend({
19. model: app.issueModel,
20. url: app.api("/issues")
21. });
22.
23. app.issueList = new app.issueCollection();
() issueCollection URL
Rockstar Developer () Building Clients (Web App) 386
JavaScript
1. app.userModel = Backbone.Model.extend({
2. urlRoot: app.api("/users"),
3. idAttribute: "_id"
4. });
5.
6. app.userCollection = Backbone.Collection.extend({
7. model: app.userModel,
8. url: app.api("/users")
9. });
10.
11. app.userList = new app.userCollection();
JavaScript
Filter
()
JavaScript
34. app.loadIssueTypes();
35. app.loadIssuePriorities();
36. app.loadIssueStatuses();
37. app.loadUserRoles();
38. }
39. });
40.
41. }, function() {
42. $("#login-alert").show();
43. });
44.
45. return false;
46. }
47. });
Issue List Nav View #nav Element Render Issue List View
#main Element Render Issue Type, Priority, Status
User List, User Role Load Property
JavaScript
View () Issue List Table View, My Issue List Table View Table
Row Issue View
Issue List View My Issue List View Issue List Collection Loop
Table Issue View Row
Issue List View Issue List Collection My Issue List View Login
JavaScript
Delete
Model destroy() Function Run Destroy
Function Model Server DELETE Request
destroy() Function Run Model Client-side
Server-side
() wait: true
Backbone Model Server-side Success Respond
Model Client-side Server-side
Server-side
Rockstar Developer () Building Clients (Web App) 397
() closeIssue() Issue
Close Server API URL localhost:3000/api/issues/status/:id
URL Pattern status
Model save() Function Run
Code
JavaScript
11.
12. app.verify(function() {
13. app.issueList.fetch({
14. success: function() {
15. var list = new issueListView();
16. $("#main").html( list.render().el );
17.
18. var nav = new navView();
19. $("#nav").html( nav.render().el );
20.
21. app.userList.fetch();
22. app.loadIssueTypes();
23. app.loadIssuePriorities();
24. app.loadIssueStatuses();
25. app.loadUserRoles();
26. }
27. });
28. }, function() {
29. var login = new loginView();
30. $("#main").html( login.render().el );
31. });
32. }
33. });
HTML
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>Issue Tracking System</title>
6. <link rel="stylesheet" href="bower_components/bootstrap/dist/
css/bootstrap.min.css">
7. <link rel="stylesheet" href="bower_components/bootstrap3-wysiwyg/dist/
Rockstar Developer () Building Clients (Web App) 399
bootstrap3-wysihtml5.min.css">
8. <link rel="stylesheet" href="css/style.css">
9. </head>
10. <body>
11. <div class="container" id="app">
12. <div id="nav">
13.
14. </div>
15. <div id="main">
16.
17. </div>
18. </div>
19.
20. <script src="bower_components/jquery/dist/jquery.min.js"></script>
21. <script src="bower_components/bootstrap/dist/js/
bootstrap.min.js"></script>
22. <script src="bower_components/bootstrap3-wysiwyg/dist/
bootstrap3-wysihtml5.all.min.js"></script>
23. <script src="bower_components/DataTables/media/js/
jquery.dataTables.min.js"></script>
24. <script src="bower_components/datatables-responsive/js/
dataTables.responsive.js"></script>
25.
26. <script src="bower_components/underscore/underscore-min.js"></script>
27. <script src="bower_components/backbone/backbone-min.js"></script>
28.
29. <script src="bower_components/moment/min/moment.min.js"></script>
30.
31. <script src="app.js"></script>
32. <script src="issues.js"></script>
33. <script src="users.js"></script>
34.
35. <script src="views/appView.js"></script>
36. <script src="views/navView.js"></script>
37. <script src="views/loginView.js"></script>
38. <script src="views/issueListView.js"></script>
39. <script src="views/issueNewView.js"></script>
40. <script src="views/issueDetailView.js"></script>
41. <script src="views/issueEditView.js"></script>
42. <script src="views/userListView.js"></script>
43. <script src="views/userProfileView.js"></script>
44. <script src="views/userEditView.js"></script>
45. <script src="views/userNewView.js"></script>
46.
47. <script>
48. app.init();
49. </script>
50. </body>
51. </html>
App
Client Web Server Run http-server NPM
Package Install Project Directory http-server Command Run
App
() Back-end Service
Service Run Back-end Service
Client Run localhost:8080 Access-Control-Allow-Origin Cross-domain
Request
View
Code
Code
JavaScript
50. app.userList.each(function(user) {
51. var view = new userView({ model: user });
52. $("tbody", that.$el).append( view.render().el );
53. });
54.
55. return this;
56. },
57.
58. newUser: function() {
59. var view = new userNewView();
60. $("#main").html( view.render().el );
61. }
62. });
JavaScript
28. }
29.
30. if(!loginId) {
31. err++;
32. $("#login-id").parent().addClass('has-error');
33. }
34.
35. if(!email) {
36. err++;
37. $("#email").parent().addClass('has-error');
38. }
39.
40. if(!password) {
41. err++;
42. $("#password").parent().addClass('has-error');
43. }
44.
45. if(password != $("#password-again").val()) {
46. err++;
47. $("#password").parent().addClass('has-error');
48. $("#password-again").parent().addClass('has-error');
49. }
50.
51. if(err) return false;
52.
53. var model = new app.userModel({
54. "fullName" : fullName,
55. "loginId" : loginId,
56. "email" : email,
57. "role" : role,
58. "password" : password
59. });
60.
61. model.save(null, {
62. wait: true,
63. success: function(res) {
64. app.userList.add(res);
65. }
66. });
67.
68. return false;
69. },
70.
71. showUserList: function() {
72. var list = new userListView();
73. $("#main").html( list.render().el );
74. }
75. });
JavaScript
59.
60. showUserList: function() {
61. var list = new userListView();
62. $("#main").html( list.render().el );
63. }
64. });
JavaScript
https://github.com/eimg/issues-backbone/archive/master.zip
Conclusion
App BackboneJS M-V-C Code Architecture Framework
BackboneJS
App
Structure
Template
Template
View Event
View View
Event
Issue Status
Priority Filter
Email Notification ()
Issue Tracking System
Source Code
Platform
Cross-platform
Software Development
http://pwdbook.com
Rockstar Developer () Building Clients (Hybrid Mobile App) 410
Hybrid App
App
HTML5, CSS3, JavaScript Web Technology Mobile Web Client
Mobile Platform
Web Technology Native Technology
Device
App Web Browser Native App Install
Rockstar Developer () Building Clients (Hybrid Mobile App) 411
()
Web Client Cordova
Mobile Device Install Hybrid App
Cordova Cordova
Web Client Hybrid App
Cordova cordova.apache.org
issues
config.xml
hooks
README.md
platforms
plugins
www
css
img
index.html
js
XML
http://developer.android.com/sdk/index.html
Android Platform
Rockstar Developer () Building Clients (Hybrid Mobile App) 414
HTML
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
10. </head>
11. <body onLoad="onLoad()">
49. <script>
50. function onLoad() {
51. document.addEventListener("deviceready", function(){
52. app.init();
53. }, false);
54. }
55. </script>
56. </body>
57. </html>
Webview JavaScript Code deviceready Event
app.init() deviceready Event
Web Client Code Device Webview
App USB
Android Device
cordova run .apk Installer
platforms/android/build Directory Hybrid App
Android Mobile Platform
Conclusion
Web App Install
App Device
Hybrid App
Device Battery Status, Network Status, Motion Sensor, Orientation, Geolocation, Camera, File,
Vibration Hardware Contact, Dialog Mobile OS
App Plugin
Cordova Plugin
http://plugins.cordova.io/
()
Software Run
Server Environment
Ubuntu Linux ()
Ubuntu Linux Installation System
Configuration Development Environment
http://u4ubook.com
( ) Deployment with Docker
Software
Development Machine
Production Server Production
Server Development Machine Environment
Software Operating System, Web Server, Database Server,
Programming Language Package Production Server
Software Package
Software Version 1.0 NodeJS 0.12.2
Software Production Server
NodeJS 0.12.2
Software Version
2.0 NodeJS 1.0 Production Server NodeJS 1.0
Version 2.0
Release
Production Server Run
Software Version 1.0 Development Machine Version 2.0
Challenge
Service Server
Service NodeJS 0.12.2
Service NodeJS 1.0 Service
Server
NodeJS Version
Package Version
Package
Challenge
Docker
17.2 Docker
Docker Tool LXC
Linux Container LXC
Virtualization VirtualBox,
VMWare Hypervisor Virtual Machine
Source docker.com
(.)
Hypervisor Host OS Kernel, Library
OS
Guest OS Kernel, Library OS
Docker Host OS Kernel, Library
OS Container OS Image OS Host OS
Host OS Library
Rockstar Developer () Deployment with Docker 421
Configuration OS
Container Kernel OS
Host OS Container OS Image
Environment Guest OS
Host OS Setting
OS Image
Docker Ubuntu Linux Install
boot2docker
Windows, Mac Operating System
Docker Install
https://docs.docker.com/installation/
Command
hello world
root@090b21537ff8:/#
Container docker ps
Terminal
$ sudo docker ps
ecc87910db51819c68414d2400e5a2a88b7090c6efb35eb1e7ee681502f8384a
Untagged: ubuntu:nodejs
Config
1. FROM ubuntu:14.04
2. RUN apt-get update && apt-get install -y mongodb
3. RUN mkdir -p /data/db
4. EXPOSE 27017
5. CMD ['/usr/bin/mongod']
http://docs.docker.com/reference/builder/
$ sudo docker ps
Container docker rm
$ sudo docker ps
Container Run Container
docker ps -a Option
root@cef44bf69c38:/# cd data
root@cef44bf69c38:/data# ls
sample.txt logo.png
Package Image
NodeJS Image MongoDB Image
Image Run
Container Link
() ExpressJS Issue Tracking System API
Image Dockerfile
Config
1. FROM ubuntu:14.04
2. RUN apt-get update && apt-get install -y nodejs nodejs-legacy
3. RUN mkdir -p /src
4. COPY . /src
5. EXPOSE 3000
6. CMD ["node", "/src/index.js"]
Package Install
/src Directory
() COPY Keyword Host Directory Image
/src Directory Directory
Issue Tracking API Source Code Image Build
Source Code Image Docker
NodeJS Install
Issue Tracking API Source Code
ubuntu:node Image
Image Run
Conclusion
Production Server Environment Challenge ()
Docker
Docker Developer
Docker RedHat, VMWare, Ubuntu, Microsoft
Docker LXC Container
App
Server Architecture
http://eimaung.com/courses
Rockstar Developer () Load Balancing with Nginx 433
Nginx Apache
Web Server Engine X
Igor Sysoev
Open Source
Resource
Web Server Web Server Reverse Proxy, Load Balancer,
Cache Server
http://nginx.org/en/download.html
$ sudo nginx
Configuration
Nginx Simplify
Config
1. http {
2. gzip on;
3. server {
4. listen 80
5. server_name example.com
6. location / {
7. # Configuration
8. }
9. }
10.
Rockstar Developer () Load Balancing with Nginx 435
11. server {
12. listen 80
13. server_name example.net
14. location / {
15. # Configuration
16. }
17.
18. location /images {
19. # Configuration
20. }
21. }
22. }
Setting
location Block
Config
1. user www-data;
2. worker_processes 4;
3. pid /run/nginx.pid;
4.
5. events {
6. worker_connections 768;
7. # multi_accept on;
8. }
9.
10. http {
11.
12. ##
13. # Basic Settings
14. ##
15.
16. sendfile on;
17. tcp_nopush on;
18. tcp_nodelay on;
19. keepalive_timeout 65;
20. types_hash_max_size 2048;
21.
22. include /etc/nginx/mime.types;
23. default_type application/octet-stream;
24.
25. access_log /var/log/nginx/access.log;
Rockstar Developer () Load Balancing with Nginx 436
Config
1. server {
2. listen 80 default_server;
3. listen [::]:80 default_server ipv6only=on;
4.
5. root /usr/share/nginx/html;
6. index index.html index.htm;
7.
8. server_name localhost;
9.
10. location / {
11. try_files $uri $uri/ =404;
12. }
13. }
Comment Comment
server Block () root Directive
/usr/share/nginx/html Directory Document Root
HTML Static Document /user/share/nginx/html Directory
() index Directive index.html index.htm Directory Index
Config
1. location /static {
2. root /usr/share/nginx/html
3. }
4.
5. location /images {
6. root /usr/share/nginx/html/images
7. }
Config
1. server {
2. server_name example.com;
3. root /var/www/example.com;
4. index index.html index.htm;
5. location / {
6. try_files $uri $uri/ =404
7. }
8. }
9.
10. server {
11. server_name example.net;
12. root /var/www/example.net;
13. index index.html index.htm;
14. location / {
15. try_files $uri $uri/ =404
16. }
17. }
Config
1. location / {
2. add_header 'Access-Control-Allow-Origin' '*';
3. add_header 'Access-Control-Allow-Credentials' 'true';
4.
5. try_files $uri $uri/ =404
6. }
http://nginx.org/en/docs/http/ngx_http_core_module.html
18.2 Proxy
Ngix
Proxy Proxy Server
User Request
App Server
example.com foo.com
Rockstar Developer () Load Balancing with Nginx 439
Reverse Proxy
Request "Server "
Proxy Client example.com Request
example.com Request foo.com example.com
Reverse Proxy App Server foo.com example.com
User foo.com example.com
App Server
Reverse Proxy
.) App Server
Access Client
Request App Server
Proxy Server
Rockstar Developer () Load Balancing with Nginx 440
.) Proxy Cache
Client Resource Proxy Cache App Server
Proxy Cache Content
App Server
Nginx Proxy
proxy_pass Directive
Config
1. location /api {
2. proxy_pass http://foo.com:3000/api;
3. }
Config
1. if ($http_user_agent ~* (wget|crawler) ) {
2. return 403;
3. }
4.
5. location /api {
6. deny 192.168.1.2;
7. proxy_pass http://foo.com:3000/api;
8. }
Config
HOST Header
() proxy_set_header Directive
HOST $host () X-Forwarded-
Proto Header Standard HTTP Header
Custom Header Nginx $scheme Variable
Protocol (HTTP HTTPS) Proxy Server App Server
Protocol Client Protocol
Config
1. upstream api_servers {
2. server api.server1.com;
3. server api.server2.com;
4. server api.server3.com;
5. }
6.
7. server {
8. # Other server configs
9. location /api {
10. proxy_pass http://api_servers;
11. }
12. }
Server
Config
1. upstream api_servers {
2.
3. least_conn;
4.
5. server api.server1.com;
6. server api.server2.com;
7. server api.server3.com;
8. }
IP Hash
Config
1. upstream api_servers {
2.
3. ip_hash;
4.
5. server api.server1.com;
6. server api.server2.com;
7. server api.server3.com;
8. }
Server Server
Upstream Setting Weight
Config
1. upstream api_servers {
2. server api.server1.com weight=3;
3. server api.server2.com;
4. server api.server3.com;
5. }
Rockstar Developer () Load Balancing with Nginx 444
Config
1. upstream api_servers {
2. server api.server1.com max_fails=3 fail_timeout=25s;
3. server api.server2.com;
4. server api.server3.com;
5. }
Cache
http Block
Config
1. proxy_cache_path /var/lib/nginx/cache levels=1:2 keys_zone=backcache:8m max_size=50m;
2. proxy_cache_key "$scheme$request_method$host$request_uri$is_args$args";
3. proxy_cache_valid 200 10m;
4. proxy_cache_valid 404 1m;
Key Hash
Config
1. location /api {
2. proxy_cache backcache;
3. proxy_cache_bypass $http_cache_control;
4.
5. proxy_pass http://api_servers;
6. }
Cache
Image, Icon, Style, JavaScript Library Static Content Cache
Content Cache Database User List
Cache Cache Database Data
Rockstar Developer () Load Balancing with Nginx 446
JavaScript
Conclusion
Nginx Reverse Proxy
Nginx Proxy Setting Load Balancing Setting
Nginx
Load Balancing HAProxy
HAProxy Nginx Application Layer Proxy Network Layer
Proxy Cache Server Varnish
Nginx Web Server Proxy Server
Cache Server
Nginx
Database Server Architecture Hardware
Storage Capacity
http://eimaung.com/courses
Rockstar Developer () MongoDB Replication and Sharded Cluster 448
MongoDB Replication
Replica Sets Master Database Server
Primary Member Slave Database Server Secondary Member
MongoDB Replica Set Member ()
Mongo Shell
Simplify
Rockstar Developer () MongoDB Replication and Sharded Cluster 450
db1.example.com
db2.example.com
db3.example.com
Ubuntu /etc/mongodb.conf
MongoDB Configuration
$ mongo
> rs.initiate()
{
"_id" : "rs0"
"version" : 1,
"members" : [
{
"_id" : 0,
"host" "db1.example.com:27017"
}
]
}
> rs.add("db2.example.com");
> rs.add("db3.example.com");
> rs.remove("db3.example.com");
Remove
Member Primary MongoDB Member
Primary
> rs.addArb("adb.example.com");
Arbiter
source: mongodb.org
> rs.conf()
{
"_id" : "rs0"
"version" : 1,
"members" : [
{
"_id" : 0,
"host" "db1.example.com:27017"
},
{
"_id" : 1,
"host" "db2.example.com:27017"
},
{
"_id" : 2,
"host" "db3.example.com:27017"
}
]
}
> cfg.members[2].priority = 0;
> rs.reconfig(cfg);
Hidden
Member hidden true
Hidden Member Priority 0
Primary Secondary
> db.runCommand("ismaster");
{
"ismaster" : false,
"secondary" : true,
"hosts" : [
"db1.example.com",
"db2.example.com"
],
"passives" : [
"db3.example.com"
],
"arbiters" : [
"db4.example.com",
Rockstar Developer () MongoDB Replication and Sharded Cluster 455
]
"primary" : "db2.example.com",
"ok" : true
}
source: mongodb.org
MongoDB Sharding
() Config
Servers, Query Routers Shards
Sharded
Cluster
source: mongodb.org
Sharded Cluster
Query Router Query Router
Shard
Shard () Config Server ()
Sharded Cluster
Domain Name
MongoDB Install
Database Server
Rockstar Developer () MongoDB Replication and Sharded Cluster 457
$ mkdir -p /data/configdb
sh.addShard()
> sh.addShard("db10.example.com:27017");
Shard Database
> sh.enableSharding("mydb");
Database Shard
config Database
config Database Sharding
MongoDB Database
MongoDB
Shard Key
Field Shard Key
_id
Field _id
Shard Data
Data Data Set Shard
> sh.status();
--- Sharding Status ---
sharding version: { "_id" : 1, "version" : 3 }
shards:
{ "_id" : "shard0000", "host" : "db1.example.com:27017" }
{ "_id" : "shard0001", "host" : "db5.example.com:27017" }
databases:
{ "_id" : "admin", "partitioned" : false, "primary" : "config" }
{ "_id" : "mydb", "partitioned" : true, "primary" : "shard0000" }
mydb.users
shard key: { "roll_no" : 1 }
chunks:
shard0001 2
shard0000 2
{ "roll_no" : { "$minKey":1 } } -->> { "roll_no" : "56000" } on : shard0001 { "t":2, "i":0 }
{ "roll_no" : 57500 } -->> { "roll_no" : "58140" } on : shard0001 { "t" : 4, "i" : 0 }
{ "roll_no" : 58140 } -->> { "roll_no" : "59000" } on : shard0000 { "t" : 4, "i" : 1 }
{ "roll_no" : 59000 } -->> { "roll_no" : { "$maxKey":1 } } on : shard0000 { "t":3, "i":3 }
> sh.status();
{
"msg" : "draining started successfully",
"state" : "started",
"shard" : "mongodb0",
"ok" : 1
}
{
"msg" : "draining ongoing",
"state" : "ongoing",
"remaining" : {
"chunks" : 42,
"dbs" : 1
},
"ok" : 1
}
somedb
Database shard0002 Primary Shard
somedb Primary
{
"msg" : "removeshard completed successfully",
"state" : "completed",
"shard" : "shard0002",
"ok" : 1
}
Conclusion
Database Replication Sharding Architecture
Architecture Replication Sharding
Rockstar Developer () MongoDB Replication and Sharded Cluster 464
http://docs.mongodb.org/manual/sharding/
Front-end, Back-end, UI Design Software
Development
Server Architecture
Full-stack Developer
http://eimaung.com/courses
Rockstar Developer () Common Server Architectures 466
Software
Programmer, Designer, Software Engineer, Web Master, Front-end Developer, Back-end Developer,
Database Administrator, System Administrator, Network Engineer
Full-stack Developer
Full-stack Developer
Specialist
Software Development Team Specialist
Full-stack Developer
Full-stack Developer
source digitalocean.com
Setup
Server
Server Hardware VPS ()
Hosting Service
Hardware Server
Scalable
RAM () Storage Capacity Server RAM HDD
Capacity Upgrade
Scale Up
Vertical Scaling Scale Up
Hardware RAM 16 GB
Server OS
Rockstar Developer () Common Server Architectures 468
HDD 16TB
Resource
source digitalocean.com
Setup
Rockstar Developer () Common Server Architectures 469
Scale Scale
Server Hardware
Server
() Security
Request App Server Load Balancer Proxy
Cache
Request App Server Proxy
Scale App
Server
App
DNS
Server Load Balancer DNS Server
IP Address IP Address Setup
Host Nginx Load Balancer App
Server Down App Server DNS
IP Address Load
Balancer Load Balancer
DNS
Cache Web Browser Client DNS
Resolver IP Address Cache
Domain Name
IP Address DNS Resolve
DNS Server IP Address
Browser Resolver
Update Cache
Router
Debug Code
Load Balancer Query Router Sharded
Cluster Configuration Architecture
Software Team Architecture
Backup Backup
Database Data Backup Database
Data Export
Rockstar Developer () Common Server Architectures 474
()
App Data Frequency Backup Routine
- Backup
Data Backup Data
Restore
Backup Backup
Backup NAS, SAN, Tape Backup Storage Device
Backup
Architecture
Backup Architecture Datacenter
Backup Backup
Backup Google Drive, Amazon S3
Cloud Storage
SAN Device
Server Architecture Backup
Failover Architecture
Procedure
Conclusion
Full-stack Developer Software Server
Architecture
Server Architecture Design
Architecture
Rockstar Developer () Common Server Architectures 476
Rockstar Developer
Rockstar Developer
Maintainable Code
Scalable Code
http://eimaung.com/courses
Rockstar Developer 479
1.
2. Code
3. Code
4.
5.
Rockstar Developer
Rockstar Developer 480
Fairway Web
Website: http://rsdbook.com
Author Profile: http://eimaung.com
Contact Email: author@rsdbook.com
Facebook: http://fb.com/RockstarDeveloperBook
()
() PDF Ebook