NodeJS: Lessons learned

#whoami

Join us!

Let's start?

Once upon a time...

Forgot!

Design Patterns

not only Object Oriented Programming

A lot of referencies

#NOT

Async

Design Patterns

We need be more specific sometimes

  function async() {
      setTimeout(function(){
          console.log(' async!');
      });
  }
  async();
  console.log('Think');

Async is more than this

Async is...

Proactor

Or your nickname "Promise"

    
    var promise = new Promise(function(resolve, reject) {
        resolve(3);
    });
    
    Promise.all([true, promise]).then(function(values) { 
        console.log(values); // # [true, 3];
    });

Observers 

&

Event Emitter

    var events = require('events');
    var eventEmitter = new events.EventEmitter();
    var five = require('johnny-five');
    var board = new five.Board();
    
    var ringBell = function ringBell() {
      // Creates a piezo object and defines the pin to be used for the signal
      var piezo = new five.Piezo(3);
      
      // Injects the piezo into the repl
      board.repl.inject({
        piezo: piezo
      });
      
      piezo.play({
        // The first argument is the note (null means "no note")
        song: [
          // Array of arrays with song data
        ],
        tempo: 100
      });
    
      // Plays the same song with a string representation
      piezo.play({
        // song is composed by a string of notes
        song: "C D F D A - A A A A G G G G - - C D F D G - G G G G F F F F - -",
        beats: 1 / 4,
        tempo: 100
      });
    }
    
    eventEmitter.on('doorOpen', ringBell);
    ...    
    eventEmitter.emit('doorOpen');

Factory


    function BaseClass(options) {  
      this.options = options;
    };
    
    function create(options) {
      return new BaseClass(options);
    };
    
    
    module.exports = {
      create: create
    };  

Streams

@substack likes this part


    process.stdin.on('readable', function () {
        var buf = process.stdin.read(3);
        console.dir(buf);
    });

    $ (echo abc; sleep 1; echo def; sleep 1; echo ghi) | node consume.js 
    <Buffer 61 62 63>
    <Buffer 0a 64 65>
    <Buffer 66 0a 67>

https://github.com/substack/stream-handbook

Would like to know more about it?

Middlewares

MIDDLE...WHAT?

    var BASIC_AUTH = [
      {
        name: process.env.BASIC_AUTH_USERNAME, 
        pass: process.env.BASIC_AUTH_PASSWORD
      },
      {
        name: process.env.BASIC_AUTH_USERNAME2, 
        pass: process.env.BASIC_AUTH_PASSWORD2
      }
    ];

    var callbackHandlerGet = function(req, res) {
        // ... your magic code =)
    }
     
    var basicAuthMultipleCredentials = require('./basic-auth-multiple-credentials');
    router.get('/multiple-credential-check', 
                basicAuthMultipleCredentials(BASIC_AUTH), 
                callbackHandlerGet);
    var auth = require('basic-auth');
    
    module.exports = function(usersAndPasswords) {
      if (!(usersAndPasswords instanceof Array)) {
        usersAndPasswords = [usersAndPasswords];
      }
    
      return function(req, res, next) {
        var credentials = auth(req);
        var authenticated = function(credentials){
          return usersAndPasswords.filter(function(registeredUser) {
            return credentials.name === registeredUser.name && 
                  credentials.pass === registeredUser.pass;
          }).length === 1;
        };
    
        if (!credentials || !authenticated(credentials)) {
          res.statusCode = 401;
          res.setHeader('WWW-Authenticate', 'Basic realm="example"');
          res.end('Access denied');
        } else {
          next();
        }
      };
    };

Why, if this way is so simple?

Middlewares

===

Reusability

Try use small modules when you can

++ @substack likes this part

https://www.quora.com/What-are-some-best-architecture-practices-when-designing-a-nodejs-system

How

To

Learn

U.M.R.U.M. - #NKO2013

NOT BAD

Real Time

doesn't

exist

LESSONS LEARNED

Know about it 

!==

use all

The micro* way

Microservices, microframeworks, micro-whatever...

Microservice +

+ Mobile App

+ Desktop App

+ WebApp

Microservice +

- Resource

- Monilithic apps

 

Modularizing everything

Be lazy, guy

... And don't forget this, ok? Or ...

Functional Programming

Making our life easy

Reactive Functional Programming

Making our life MUCH easier

Proactor?

Promises?

Monads

    // Example in http://codepen.io/willmendesneto/pen/Iguor
    $.get('http://worldcup.sfg.io/matches', function(data){
      var playgame  = ''; 
      data.forEach(function(item){
        if (item.status === 'completed') {
          playgame = item.home_team.country + 
                     ' ' + item.home_team.goals + 
                     ' x ' + item.away_team.country + 
                     ' ' + item.away_team.goals;

          console.log(playgame);
        }
      });

    }, 'json');
      
      $.get('http://worldcup.sfg.io/matches', function(data){
        var completePlays = [], 
            playgame = '';

        data.filter(function(item, i){
          if (item.status === 'completed') {
            return item;
          }
        }, []).sort(function(a,b){
          return new Date(a.datetime) - new Date(b.datetime);
        }).forEach(function(item, i){
          playgame = item.location + 
                     ': ' + item.home_team.country + 
                    ' ' + item.home_team.goals + 
                    ' x ' + item.away_team.country + 
                    ' ' + item.away_team.goals;

          completePlays.push(playgame);
        });
       console.log(completePlays.join(''));
      });
  function WorldCup(){
    this.completePlays = [];
    this.url = 'http://worldcup.sfg.io/matches';
  }

  var playgame = '';

  WorldCup.prototype.loadData = function() {
    var self = this
    $.get(this.url, function(data){
      data = self.filterData(data);
      self.listsPlays(data);
      console.log(self.completePlays.join('\n'));
    });
  };

  WorldCup.prototype.listsPlays = function(data) {
    var self = this;
    data.forEach(function(item, i){
      playgame = item.location + 
                ': ' + item.home_team.country + 
                ' ' + item.home_team.goals + 
                ' x ' + item.away_team.country + 
                ' ' + item.away_team.goals;

      self.completePlays.push(playgame);
    });
  };


  
    
        
            
                
                    
                    var WorldCup = new WorldCup();
                    
                    WorldCup.loadData();

Javascript everywhere

why not?

#codetime

Build checker

One idea?

Always bet on JS
#thanks

Wilson Mendes

@willmendesneto

Made with Slides.com