Deploying Node.js app to Heroku


# login to Heroku if not SSH issues!
heroku login

# clone git repo to local drive
git clone git://abc.git

# install packages & build it
cd abc
npm install

# if gitignore found
remove contents of .gitignore

# important creates remote heroku branch & generates a dynamic name for the repo
heroku create
git push heroku master



#after changes
git add .
git commit -m “add local changes”
git push heroic master
heroku open or  heroku open cool
Advertisements

filter component

1. All urls to 1 route

Router.map(function() {
  this.route('about', {path: '/'});
  this.route('about', { path: '/*wildcard' });
});

2. Dom Manipulation

// in any controller
Ember.$('#component-x').val('My Value');

3. Adapter: rental.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  'namespace': 'api'
});

4. Template: index.hbs

<div class="jumbo">
  <div class="right tomster"></div>
  <h2>Welcome!</h2>
  <p>
    We hope you find exactly what you're looking for in a place to stay.
    <br>Browse our listings, or use the search box above to narrow your search.
  </p>
</div>

{{input value=filterText type='text' placeholder='Search City'}}
  {{#unless filteredResults.length}}
    <h4>no record matched your criteria</h4>
  {{/unless}}

  <ul>
    {{#each filteredResults as |item|}}
      <li>{{item.id}} {{item.attributes.city}}</li>
    {{/each}}
  </ul>

5. Route: index.js

import Ember from 'ember';

export default Ember.Route.extend({
  filterText: '',

  setupController(controller, model) {
    this._super(controller, model);
    controller.set('filterText', this.get('filterText'));
  },

  queryParams: {
    search: {
      refreshModel: true
    }
  },

  beforeModel: function(transition) {
    // console.log('before model: '+transition.queryParams.search);
    this.set('filterText', transition.queryParams.search);
  },

  model: function(params) {
    var endPoint = 'http://localhost:4200/api/deals';
    var results = [];

    endPoint = (params.search)? endPoint+'/city='+params.search : endPoint;

    $.ajax({
      url: endPoint,
      type: 'GET',
      accepts: 'application/json',
      success: function(data) {
        if(data.rentals) {
          data.rentals.forEach(function(deal) {
            results.addObject(deal);
          });
        } else if(data.data === 'no records found'){
          console.log('No results found');
        } else {
          data.data.forEach(function(deal) {
            results.addObject(deal);
          });
        }
      },
      error: function() {
          console.log('DEBUG: GET Deals Failed');
      },async:false
    });
    return results;
  }
});

6. Controller: index.js

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['search'],

  onFilterTextChange: function() {
    Ember.run.debounce(this, this.applyFilter, 0);
  }.observes('filterText'),

  applyFilter: function() {
    this.set('search', this.get('filterText'));
    console.log('search set: ' + this.get('search'));
  },
  
  filteredResults: function() {
    return this.get('model');
  }.property('search'),
});

7. Mock Response(http-mock): rentals.js

/*jshint node:true*/
module.exports = function(app) {
  var express = require('express');
  var rentalsRouter = express.Router();
  var rentals = [
      {
        type: 'rentals',
        id: 1,
        attributes: {
          title: 'Grand Old Mansion',
          owner: 'Veruca Salt',
          city: 'San Francisco',
          type: 'Estate',
          bedrooms: 15,
          image: 'https://upload.wikimedia.org/wikipedia/commons/c/cb/Crane_estate_(5).jpg'
        }
      }, {
        type: 'rentals',
        id: 2,
        attributes: {
          title: 'Urban Living',
          owner: 'Mike Teavee',
          city: 'Seattle',
          type: 'Condo',
          bedrooms: 1,
          image: 'https://upload.wikimedia.org/wikipedia/commons/0/0e/Alfonso_13_Highrise_Tegucigalpa.jpg'
        }
      }, {
        type: 'rentals',
        id: 3,
        attributes: {
          title: 'Downtown Charm',
          owner: 'Violet Beauregarde',
          city: 'Portland',
          type: 'Apartment',
          bedrooms: 3,
          image: 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Wheeldon_Apartment_Building_-_Portland_Oregon.jpg'
        }
      }
    ];

  rentalsRouter.get('/', function(req, res) {
    res.send({
      rentals
    });
  });


  rentalsRouter.post('/', function(req, res) {
    res.status(201).end();
  });

  /*rentalsRouter.get('/:id', function(req, res) {
    res.send({
      '':req.params
    });
  });*/

  rentalsRouter.get('/:city', function(req, res) {
    let val = req.params.city.split("=");
    let filteredRentals = rentals.filter(function(i) {
      return i.attributes.city.toLowerCase().indexOf(val[1].toLowerCase()) !== -1;
    });

    if(filteredRentals.length>=1) {
      res.send({
        'data': filteredRentals
      });
    } else {
      res.send({
        'data': 'no records found'
      });
    }

    
  });

  rentalsRouter.put('/:id', function(req, res) {
    res.send({
      'rentals': {
        id: req.params.id
      }
    });
  });

  rentalsRouter.delete('/:id', function(req, res) {
    res.status(204).end();
  });

  // The POST and PUT call will not contain a request body
  // because the body-parser is not included by default.
  // To use req.body, run:

  //    npm install --save-dev body-parser

  // After installing, you need to `use` the body-parser for
  // this mock uncommenting the following line:
  //
  //app.use('/api/rentals', require('body-parser').json());
  app.use('/api/rentals', rentalsRouter);
};

Journal – publish bower package; setup ember mock

1. Publish Bower Package

Bower was started by twitter.
https://bower.io/docs/creating-packages/

2. Simple Ember App

Super Rentals

3. Mocks with EmberJS

EmberJS comes with ExpressJS (internally, http-mock) here are steps to setup a mock. Once setup it works like a real service & it actually be used to build REST API for your backend if it is fueled with real data.

  • generate ember project with ember-cli
  • generate an express route
    ember g http-mock destinations
  • to view: http://localhost:4200/api/destinations
  • Unlike fixtures, this helps you test your Adapter as well
  • setting up a mock response
// server/mocks/destinations.js
/*jshint node:true*/
module.exports = function(app) {
  var express = require('express');
  var destinationsRouter = express.Router();

  destinationsRouter.get('/', function(req, res) {
    res.send({
      'destinations': [
		{
			id:'001',
			loc: 'london'
		}, {
			id:'002', 
			loc: 'rotterdam'
		}, {
			id:'003', 
			loc: 'amsterdam'
		}
	  ]
    });
  });

  destinationsRouter.post('/', function(req, res) {
    res.status(201).end();
  });

  destinationsRouter.get('/:id', function(req, res) {
    res.send({
      'destinations': {
        id: req.params.id
      }
    });
  });

  destinationsRouter.put('/:id', function(req, res) {
    res.send({
      'destinations': {
        id: req.params.id
      }
    });
  });

  destinationsRouter.delete('/:id', function(req, res) {
    res.status(204).end();
  });

  // The POST and PUT call will not contain a request body
  // because the body-parser is not included by default.
  // To use req.body, run:
  //    npm install --save-dev body-parser

  // After installing, you need to `use` the body-parser for
  // this mock uncommenting the following line:
  //app.use('/api/destinations', require('body-parser').json());
  app.use('/api/destinations', destinationsRouter);
};

Node bits

Parse a Markup & read contents of a folder

const md = require('commonmark');
const fs = require('fs-extra');


const parser = new md.Parser();
const renderer = new md.HtmlRenderer();

var input = '# This is a header\n\nAnd this is a paragraph';
var content = renderer.render(parser.parse(input)).trim();

console.log(content);

// __dirname
fs.readdir(__dirname, function (err, files) {
 if (err) throw err;
 for (var index in files) {
    console.log(files[index]);
 }
});
// package.json
{
  "author": "Hamzeen H ",
  "bin": "hello.js",
  "bugs": {
    "url": "https://github.com/hamzeen/hamzeen.github.io/issues"
  },
  "dependencies": {
    "commonmark": "^0.25.0",
    "fs-extra": "^0.29.0"
  }
}

Build an Ember Project and Launch

// build.js
var sys = require("sys"),
    exec = require('child_process').exec,
    util = require('util');

var visits = 0;
var result = exec("ember s --port=4300", function(err, stdout, stderr) {
  //sys.puts("1::");
});
//sys.puts("Obj:: "+util.inspect(result, false, null));

result.stdout.on('data', function(data) {

  visits += 1;
  if(visits == 5) {
    sys.puts("1 [Serving at 4300]");

    var spawn = require('child_process').spawn
    var sp = spawn('open', ['http://localhost:4300']);
    sp.on('exit', function (code) {
      sys.puts("2 [Opened Browser]");
    });
  }
});

Port an Ember App to Cordova

1. Pre-Requisites

1.1. Ember Cli
$sudo npm install -g ember-cli

1.2. Cordova
$sudo npm install -g cordova

1.3. Also consider
Git, Node.js (with NPM), Bower, Ember CLI, PhantomJS

2. create ember project

$ember new labs

3. include ember-cordova-cli in package.json

DevDependencies
“ember-cli-cordova”: “0.0.15”,

4. alter config/environment.js

modulePrefix: ‘hello’,
environment: environment,
baseURL: ‘/’,
locationType: ‘hash’,
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. ‘with-controller’: true
}
},

APP: {
// Here you can pass flags/options to your application instance
// when it is created
},

cordova: {
rebuildOnChange: false,
emulate: false
}

5. Generate Cordova Proj (reverse domain name)

sudo ember generate cordova-init com.hamzeen.hello –platform=android

6. Open Existing Proj

ember cordova:prepare

7. Open iOS Porject in Xcode

ember cordova:open

8. Build for target platform

$sudo ember cordova:build –environment=production –platform=android

9. Additional

9.1. full access
$chmod 777 -R /dir

9.2. To modify npmrc for proxies and npm registry
$vi ~/.npmrc

10. Live debug

visit this url on chrome
chrome://inspect/#devices

Reference:

introduction:

ember-cli-cordova
https://github.com/poetic/ember-cli-cordova

for iOS
http://dreamingin.codes/article/merging-ember-cli-cordova-and-make-it-emulate-ios-live/

http://lelandbatey.com/posts/2015/02/ember-and-cordova