Create a Mongo/Node API in 10 minutes!

Using Heroku, you can get the barebones of a Node/Mongo API in just under 10 minutes!

    Prerequisites

  • A registered Heroku account
  • Install Heroku CLI
  • Access to your Heroku dashboard
  • Step 1 – Create and navigate to project directory

    Wherever you want your project to be. Perhaps c:\My Cool Things\API or /Users/hank/projects/api-project.

    Step 1 – Create Heroku app

    From the command line of your choice, from your project directory:

    $ heroku create

    You’ll be presented with a nifty server name. Something like falling-wind-1234 or similarly zen-like.

    Step 2 – Create app structure

    For a barebones API you’ll need just just 3 basic things.

    2a – Procfile
    Needed for Heroku to run the app. The contents of this file is just one line for now.

    web: node index.js

    2b – package.js
    This manages your node packages and will be managed automatically via your

    $ npm install

    commands you make later.

    Type

    $ npm init

    and hit enter through all of the prompts. The default values will be fine for now.

    2c – index.js
    The starting point of your app will start and connect to your mongo/node server. We will create this in Step 4!

    Step 3 – Install dependencies

    Since this is a barebone API, we will have just 3 dependencies: mongodb and hapijs

    Back at the command line, type

    $ npm install mongodb --save
    $ npm install hapijs --save
    $ npm install mongoose --save

    Step 4 – Create index.js

    const Hapi = require('hapi');
    const Mongoose = require('mongoose');
    
    // Create a server with a host and port
    const server = new Hapi.Server();
    
    var mongoUri = process.env.MONGODB_URI || 'mongodb://YOUR_MONGO_URI';
    var serverPort = process.env.PORT || 8080;
    
    Mongoose.connect(mongoUri, function(err) {
    	if (err) {
    		console.log(err);
    		process.exit(1);
    	}
    
    	server.connection({
    		port: serverPort
    	});
    
    	// GET locations route
    	server.route({
    		method: 'GET',
    		path:'/hello',
    		handler: function (request, reply) {
    			return reply("Hello, this is my API");
    		}
    	});
    
    	// Start the server
    	server.start((err) => {
    
    		if (err) {
    			throw err;
    		}
    		console.log('Server running at:', server.info.uri);
    	});
    });
    
    

    Step 5 – Deploy!

    To send it up to your Heroku app, type

    $ git commit -am "My 10 minute API!"
    $ git push heroku

    After the app is built, you can navigate to your Heroku app url (for example, https://guarded-bear-24888.herokuapp.com/) and see the results!

    Using our example, navigating to just the base url will produce a 404, but a valid response nonetheless! If you navigate to the base url followed by /hello, you should get our hello world response.

    Next steps for your newly minted API could be to create some routes that interact with your mongo instance, make some hapijs views or publish your code to your personal github repo.

Getting Started: meteor.js

Introduction

meteor.js is a library that allows you to make real-time web applications from start to finish without any other supporting libraries or tools. When you install meteor.js, you get everything you need to develop both the client and server side of your application. That’s quite a big deal in this age of being faced with having to cherry pick from the many client/server-side technologies available today for your application.

The downside to using meteor.js is that it requires a server to be running the meteor process. So if you have any sort of VPS (Virtual Private Server) hosting (HostMonster, DreamHost, etc), then you may need to build your meteor app elsewhere.

For the sake of this post, we will be deploying to meteor’s free development hosting option.

Installing

From your terminal of choice (mac, SSH, etc), simply install meteor.js via curl like so:

curl https://install.meteor.com/ | sh

For windows, you can download the installer https://www.meteor.com/install. If you are doing this in a shared environment, such as a site on HostMonster, you’ll end up with a warning message with a few options.

Couldn't write the launcher script. Please either:

(1) Run the following as root:
cp "{Environment Specific Path}/.meteor/packages/meteor-tool/1.0.35/meteor-tool-os.linux.x86_64/scripts/admin/launch-meteor" /usr/bin/meteor
(2) Add "$HOME/.meteor" to your path, or
(3) Rerun this command to try again.

Typically, due to not having root access, your best bet is #2. Note: the areas bolded above may be different in your environment. Adjust accordingly. To do this, type this in your terminal window:

PATH=$PATH:$HOME/.meteor

You can test this right away by typing meteor in your terminal. If you were successful, it will give you a warning about not being in a project directory. This only changes the path for this particular terminal session. If you want to make it more permanent, you can edit your .bashrc file. My .bashrc file is located at ~/.bashrc and look something like this after adding the meteor path to it.

alias php="php-cli"
export HPATH=$HOME
export PATH=$PATH:$HPATH/.meteor

Deploy Your First meteor.js Application

Navigate to the directory you want to create your first meteor.js application. In my case, I created a subfolder in my public_html directory. Once there, create your first app:

meteor create project-name

meteor.js will do it’s thing and after a few seconds, your barebones meteor app will be ready to go. By default, meteor will create a build directory (.meteor), and html, css, and js files. Depending on your meteor version you may get slightly different contents in your html/js.

At this point you can deploy your project to meteor’s free hosting by typing

meteor deploy project-name.meteor.com

and after a few prompts, your project will be visible at http://project-name.meteor.com.

Applying Some meteor.js Fundamentals

Once you’re done basking in the glory of your first published meteor app, we will start poking at the html/js files. In your html file, you will see an example of meteor’s template structure.

<body>
  {{> hello}}
</body>

<template name="hello">
  <h1>Hello World!</h1>
  {{greeting}}
  <input type="button" value="Click" />
</template>

{{> hello}} will output the contents of everything inside of <template name="hello"></template>. Inside the hello template that there is a template variable named greeting. This corresponds to some code in the project-name.js file.

if (Meteor.isClient) {
Template.hello.greeting = function () {
return "Welcome to demo.";
};
...
}

You can have regular javascript variables, but in order to make it a template variable it can be created a variety of ways.

Template.hello.greeting = function() {
return 'This is a greeting';
}

//-- standard javascript variable
var foo = 'This is foo.';
//-- ..turned template variable
Template.hello.foo = function() {
return foo;
}

Template.hello.sum = function() {
a  = 2;
b = 2;
c = (a + b);
return c;
}

One of the most efficient ways is to create template variables via helpers.

Template.hello.helpers({
list: [{'label': 'One'    }, {'label': 'Two'}, {'label': 'Three'}],
sum: function() {
return (2+2);
}
});

Once we have some template variables defined, we can output them in our template. Depending on the kind of variable, we can do this a few ways. Using our example variables above, our modified template could look like this;

<template name="hello">
<h1>{{greeting}}</h1>
<ul>
{{#each list}}
<li>{{label}}</li>
{{/each}}
</ul>
<h3>{{sum}}</h3>
<p>{{foo}}</p>
</template>

Since list is an array of objects, we can use meteor’s {{#each}} to iterate through it and output each item’s properties.

Now you have the basics of meteor.js down. Keep in mind that meteor.js excels at real-time applications. Chat rooms, messaging, anything the could benefit from live data. As web applications start to mature past the already robust features of AJAX/REST driven development, meteor.js could be one of the key players in the next stack of web development.

Quickstart: Bootstrap

Impress your friends when you show them a page that looks fantastic across any and all devices and screens! Start the timer! You’ll be a maker of responsive pages in 15 minutes!

1. Get Bootstrap & jQuery

For Bootstrap, you can either download it and include it or use the code below to pull it from Bootstrap’s CDN buddy, MaxCDN.

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">


<!-- Optional theme -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">


<!-- Latest compiled and minified JavaScript -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

Same story with jQuery. You can use Google’s hosted library or download your own copy. Here is the Google option:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

2. Create an HTML grid layout

Your page must use the HTML5 doctype so make sure it uses the same doctype listed below.

<!DOCTYPE html>
<html>
... jQuery/Bootstrap scripts/css from above...
<body>
<!-- responsive layout -->
</body>
</html>

Responsive frameworks usually work within some sort of grid. For Bootstrap, your layout is separated into 12 %-based columns equaling 100% of the container. You can divvy up your content however you see fit within those columns via the different column css classes.

There are 3 main column classes. There is .col-sm-n for 768px and up, .col.md-n for 992px and up, and .col.lg-n for 1200px and up. Keep in mind, in the class names above, n is the number of columns. So .col-sm-3, .col-md-8, .col-lg-4 are all valid examples.

You can apply multiple column classes to get different layouts based on the width of the screen. To use the same layout across the board, you would use one of the lowest column classes, .col-sm-n.

For example, if you want your layout to have a left nav that takes up 3 columns and the rest of the content to take the remaining 9 columns. 9 + 3 = 12.

<div class="container">
<div class="row">
<div class="col-sm-3">Left Content</div>
<div class="col-sm-9">Right Content</div>
</div>
</div>

If you want the left content and right content to both take up the width of the screen that is 992px or less (.col-sm-n), but maintain the 3 and 9 column layout for anything above (.col-md-n and .col-lg-n).

<div class="container">
<div class="row">
<div class="col-md-3">Left Content</div>
<div class="col-md-9">Right Content</div>
</div>
</div>

Quickstart: Laravel 4

Your mileage may vary with this particular quickstart depending on your host. I am using hostmonster, a fairly poor choice for current web development trends, but we aren’t exactly creating the next InstaBookSpaceGramChat here.

1. Download Composer

In SSH, navigate to  the root of your project folder and run the following to download Composer.

curl -sS https://getcomposer.org/installer | php

2. Create your Laravel project

Before you go all copy-pasta crazy down below, make sure to replace your-project-name with whatever it is you are making.

By default, the command to install Laravel project is:

composer create-project laravel/laravel your-project-name --prefer-dist

For my particular environment, I needed to add php and change composer to composer.phar. Again, this is more than likely due to my shared server environment. The updated command looked something like this:

php composer.phar create-project laravel/laravel your-project-name --prefer-dist

Update 09/10/14: For Dreamhost servers, I ended up installing Composer in ~/bin so my Composer command ended up being php ~/bin/composer.phar. I solved this mess by creating an alias via alias composer='php ~/bin/composer.phar'. This allowed me to run composer all over the place.

3. Make /public directory work properly

At this point, your Laravel app is ready to go. Unfortunately, by default, everything needs to be accessed via /public. So if http://www.instabookspacegramchat.com is pointing to your new Laravel project directory, you would need to go to http://www.instabookspacegramchat.com/public to see your new project at work.

This, to me, is a horrible flaw with the base Laravel install. To get around it you can either a) set your document root to /public for your domain or b) create an .htaccess file in your project root.

For option b, I used the following in my newly created .htaccess file:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]

4. Create a view and route

If you open up your /app/routes.php file, you’ll see that your default route is being handled by the hello view. The hello view lives in /app/views as hello.php.

To create a view and route to call your very own, you’ll need to go back to your /app/routes.php file and add the following:

Route::get('/foo', function()
{
return View::make('foo');
});

The parameter of View::make() refers to the view. In our case, foo refers to /app/views/foo.php

Keep in mind this is one of the more basic methods of creating a route.  In your later Laravel travels, your route-fu will be much stronger.

Next we need to make our foo view. Save & close your routes.php and create /app/views/foo.php. Throw whatever HTML you want to in this new view and hop on over to http://[url]/foo.

5. Next Steps

  • Creating Blade templates
  • Advanced routing
  • Creating controllers
  • Creating models

Quickstart: Ember.js

Need to dive into the MVC Javascript web application framework known as Ember.js and only have 10 minutes? Look no more!

The following is all done in the same page. In my case, it is index.html.

1. Get Ember.js, Handlebars.js and jQuery


<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://builds.emberjs.com/tags/v1.3.0/ember.js"></script>

2. Start your application

In this case myApp is our application. myApp can be changed to whatever you want. Just be sure to keep it in mind to reference later.

<script type="text/javascript">
window.myApp = Ember.Application.create();
</script>

3. Setup a route or two

<script type="text/javascript">
myApp.Router.map(function() {
this.resource('index', { path: '/' });
this.resource('about', { path: 'about' });
});
</script>

The first parameter of this.resource() corresponds to a <script type="text/x-handlebars"> element with a matching data-template-name attribute.

For example:

this.resource('foo', { path: '/foo-page' });

refers to:

<script type="text/x-handlerbars" data-template-name="foo">
<p>some html...</p>
</script>

and would be accessed by http://[your url]/foo-page.

4. Make your views

<html>
<body>
<script type="text/x-handlebars" data-template-name="index">
<h1>Index Page</h1>
<p>{{#link-to 'about'}}about{{/link-to}}</p>
</script>


<script type="text/x-handlebars" data-template-name="about">
<h1>About Page</h1>
<p>{{#link-to 'index'}}home{{/link-to}}</p>
</script>
</body>
</html>

View the final product here.

5. Next Steps

  • Exploring Handlebars
  • Data Binding/Modeling