module design pattern i.e. express js

43
02 | Understanding Module Design Pattern 03 | Express.js Ahmed Assaf | Senior Software Engineer

Upload: ahmed-assaf

Post on 15-Apr-2017

249 views

Category:

Software


5 download

TRANSCRIPT

Page 1: Module design pattern i.e. express js

02 | Understanding Module Design Pattern 03 | Express.js

Ahmed Assaf | Senior Software Engineer

Page 2: Module design pattern i.e. express js

Setting Expectations

Target Audience Web Developers Web Designers Developers with experience using other service side languages such as

PHP, ASP.NET, Python, Ruby etc.

Page 3: Module design pattern i.e. express js

Module Overview Exports a Namespace Exports a Function Exports a Higher Order Function Exports a Constructor Exports a Singleton Extends a Global Object Applies a Monkey Patch

Page 4: Module design pattern i.e. express js

Module Design Patterns Modules are still JavaScript Possess many of the challenges of pre-ES6 Javascript Design Patterns to help with

Encapsulation Stable Interface

Page 5: Module design pattern i.e. express js

Exports a Namespace

Page 6: Module design pattern i.e. express js

Exports a Namespace Module returns an object Object contains properties and functions Calling code can refer to properties and execute functions

Page 7: Module design pattern i.e. express js

Simply return an object with whatever properties and functions the calling code should have access to

//private module stuff can happen here

//then return an objectmodule.exports = { property1: 'value', property2: 'value', function1: function(){ … } function2: function(){ … }}

Page 8: Module design pattern i.e. express js

Core 'fs' Node module returns an objectreadFile and ReadStream are functions of the returned objectBoth are accessible from this calling functionAnalogous to static classes and members in other languages

var fs = require('fs');

fs.readFile('./file.txt', function(err, data) { console.log("readFile contents: '%s'", data);});

new fs.ReadStream('./file.txt').on('data', function(data) { console.log("ReadStream contents: '%s'", data);});

Page 9: Module design pattern i.e. express js

Exports a Function

Page 10: Module design pattern i.e. express js

Exports a Function Factory function Gives you instancing since all variables are encased in a closure Closure is run for each require() Revealing Module Pattern you may have used in client side JavaScript ProTip

If you don’t need instancing – export a namespace If you need instancing – export a constructor

Page 11: Module design pattern i.e. express js

module.exports = function(options) {options = options || {};var loggingLevel = options.loggingLevel || 1;

function logMessage(logLevel, message) {if(logLevel <= loggingLevel) {

console.log(message);}

}return { log: logMessage };

}

Page 12: Module design pattern i.e. express js

DEMO

Page 13: Module design pattern i.e. express js

Exports a Higher Order Function

Page 14: Module design pattern i.e. express js

Exports a Higher Order Function Like the former, but also receives a function that affects the behavior of the function it returns Express middleware is a great example - functions are provided and the middleware function is

returned

Page 15: Module design pattern i.e. express js

Chaining is possible with the app object because the middleware functions each return it.

var app = require('express')();

app.use('/route1', function(res, req, next) { //do something next();});

app.use('/route2', function(res, req, next) { //do something next();});

Page 16: Module design pattern i.e. express js

Exports a Constructor

Page 17: Module design pattern i.e. express js

Exports a Constructor Constructor function creates instance Prototype used to define behavior Caller creates instance with new keyword Multi instance

Page 18: Module design pattern i.e. express js

DEMO

Page 19: Module design pattern i.e. express js

Exports a Singleton

Page 20: Module design pattern i.e. express js

Exports a Singleton Instantiates object before returning it Causes all calling modules to share a single object instance

Page 21: Module design pattern i.e. express js

When an object is instantiated before it's returned, it acts as a singleton.

function Something() { …}

module.exports = new Something();

Page 22: Module design pattern i.e. express js

Mongoose is one example of a good use of the singleton pattern

var mongoose = require('mongoose');mongoose.connect('mongodb://localhost/test');

var Cat = mongoose.model('Cat', { name: String });

var kitty = new Cat({ name: 'Zildjian' });kitty.save(function (err) { if (err) // ... console.log('meow');});

Page 23: Module design pattern i.e. express js

Extends a Global Object

Page 24: Module design pattern i.e. express js

Extends a Global Object Modifies an existing type i.e. String Doesn’t have to export anything Makes for nice calling syntax but can be difficult to track down source in large project Frowned upon in open source packages

Page 25: Module design pattern i.e. express js

Applies a Monkey Patch

Page 26: Module design pattern i.e. express js

Applies a Monkey Patch A monkey patch is the dynamic modification of a class or object at runtime to fix a bug in

existing code Similar to previous pattern (extends a global object) but affects cached node modules

Page 27: Module design pattern i.e. express js

The winston logger defaults all profiling statements to the info level and you can’t changeA quick monkey patch allows you to log data out as any log level you want and replace the built in functionality without forking the code base

winston.Logger.prototype.profile = function(id) {

// Altered behvaior or winston loggers profile function

};

Page 28: Module design pattern i.e. express js

Summary Exports a Namespace Exports a Function Exports a Higher Order Function Exports a Constructor Exports a Singleton Extends a Global Object Applies a Monkey Patch

Page 29: Module design pattern i.e. express js

03 | Express.js

Page 30: Module design pattern i.e. express js

What is Express? Express is a minimal, open source and flexible node.js web app framework designed to make

developing websites, web apps and APIs much easier.

Page 31: Module design pattern i.e. express js

Why use Express?

Express helps you respond to requests with route support so that you may write responses to specific URLs.

Supports multiple templating engines to simplify generating HTML.

Page 32: Module design pattern i.e. express js

Installing and Using Express

Page 33: Module design pattern i.e. express js

Installing and Using Expressnpm install expressnpm install jade

Page 34: Module design pattern i.e. express js

Creating a Simple REST API

Page 35: Module design pattern i.e. express js

Explanation of Routes

A router maps HTTP requests to a callback. HTTP requests can be sent as GET/POST/PUT/DELETE, etc. URLs describe the location targeted. Node helps you map a HTTP GET request like:

http://localhost:8888/index To a request handler (callback)

app.get('/index', function (req, res) {});

Page 36: Module design pattern i.e. express js

Creating a Simple Express Applicationvar express = require('express'); var app = express();

app.get('/', function (req, res) {     res.json({message:'hooray! welcome to our api!'});});

app.listen(process.env.PORT || 8080);

Page 37: Module design pattern i.e. express js

DEMOCreating a simple REST API with Express Framework

Page 38: Module design pattern i.e. express js

DEMOUsing the express-generator package.

Page 39: Module design pattern i.e. express js

DEMOUsing Express for Multiple Pages with Query Parameters

Page 40: Module design pattern i.e. express js

Building a RESTful API for DogsResource GET PUT POST DELETE

Collection URI, such as http://api.example.com/v1/dogs/

List all the dogs

Replace all the dogs with a new collection of dogs.

Create a new dog in the collection.

Delete the entire dog collection.

Element URI, such as http://api.example.com/v1/dog/1

Get a specific dog.

Replace a dog in the collection with another dog.

Not used.Delete the dog from the collection.

Page 41: Module design pattern i.e. express js

DEMOUsing Express to build a RESTful API

Page 42: Module design pattern i.e. express js

Resources

Express Framework http://expressjs.com/ Intro to Express

http://code.tutsplus.com/tutorials/introduction-to-express--net-33367 Jade Templates http://jade-lang.com/tutorial/ JavaScript and Jade Templating

http://www.slideshare.net/wearefractal/jade-javascript-templating

Page 43: Module design pattern i.e. express js

Resources Using Node.js with Visual Studio Code #MVA Course By

Stacey Mulcahy | Senior Technical Evangelist Rami Sayar | Technical Evangelist

Mastering Node.js Modules #MVA Course By Chris Kinsman | Chief Architect at PushSpring

https://blog.jcoglan.com/2013/03/30/callbacks-are-imperative-promises-are-functional-nodes-biggest-missed-opportunity/

http://code.tutsplus.com/tutorials/using-nodes-event-module--net-35941 http://spin.atomicobject.com/2012/03/14/nodejs-and-asynchronous-programming-with-

promises/

Github repo: https://github.com/AhmedAssaf/NodeMVA From : https://github.com/sayar/NodeMVA