Vatican.js 1.3, get your API up and running without writing a single line of code

A few weeks ago, I released version 1.3 of Vatican.js, my microframework design to ease the process of writing APIs in Node.js.
My goal with Vatican has always been speed of development. And the main focus on version 1.3 is getting up and running as fast as you can.
With that in mind, what are the basics things that an API would need to have to be usable (we’re talking MVP level of usable):

  • Web server: We need something to hit, so the web server is kind of important.
  • Resource handlers: Vatican’s focus are REST APIs, so resources are a basic need here.
  • A database connection: Because we want to save persist information from the get go
  • Resource representation for db: We’re working with an ORM so we need an object representation of the data

That’s about it, if we want to test a concept, having all of that out of the box, would be pretty helpful, don’t you agree?
Back with version 1.2 of Vatican, you’d have the first two out of the box, but the resource handlers wouldn’t do anything. So that wasn’t good enough.
Now with verson 1.3, Vatican will auto-generate as much code as it can for you, so the basic CRUD actions will be there already. Currently the storage engine used is MongoDB, with the Mongoose module but I’m planning on allowing for other options in the future.

How do we do that?

To get there, we’ll need to use the CLI tools that come with Vatican. First we’ll create a new project by doing:

$vatican new api-project

With that command, Vatican just created the project’s folder, a handlers folder inside it, where all the resource handlers will be saved, a package.json file with the basic dependencies needed, and the index.js file, also, with the minimun code needed for the project to start up.
Once this is done, and from within the new folder, we’ll need to create the resources. It helps if you know beforehand how that resource should look like (which attributes it’ll have, and what you’ll want to do with it).

So, lets go with two simple resources for the example:

Book

  • Title: string
  • ISBN: string
  • Author: Reference to Author resource
  • Stars: integer

And Author

  • First name: string
  • Last name: string
  • Address: string

The actions will be the following:

  • For books: Create a book, list all books and remove a book by it’s id and update it’s author.
  • For authors: We’ll want to add new authors and list them up

So with this in mind, the commands we’ll need are the following:

$ vatican g book -a title:string isbn:string author:Author stars:integer -m newBook:post listBooks:get deleteBook:delete addAuthor:put
$ vatican g author -a first_name:string last_name:string address:string -m createAuthor:post listAuthors:get

The lines from above have just created 4 files, the resource handlers inside the handlers folder, and the mongoose schemas inside the schemas folder.

Now just by running npm install and then node index.js the API will be up and running on port 8753.

Is that it?

Well, almost, the code for the newBook,listBooks,deleteBook,createAuthor and listAuthors method as generated by Vatican, based on the names of the methods, it tried to guess what they did.
The only coding you’ll have to do, is the one for the method addAuthor inside the books resource handler. That will be all up to you.

For more information, please refer to the full documentation at:

Final thoughts

So, what version 1.3 of Vatican is trying to do, is shaving off developing time by auto generating the simple things, it’s not going to guess the full extent of what you’re trying to achieve (not yet anyways!) but it’ll do it’s best to help you get there.

Node.js::Getting around Github Raw resources limitations

Node.js::Getting around Github Raw resources limitations

It’s a very common scenario: you finally find the file you’re looking for to start using on your website (be it a jquery plugin, an angular directive, or whatever you can include on your website) on Github, navigate to that file, hit the “raw” link and then copy the URL.

But when you try it on your site, it won’t work… , you check the Network tab on your favourite browser and you see that the resource is being interpreted as a plain text file, so your browser doesn’t know what to do with it.

Not cool Github! (well, to be fair, I don’t think they intended their site to act as a CDN).

Two easy ways to get around raw.github.com limitations to use files on our websites.

I’ll quickly go over two solutions to this problem…

Online solution: rawgithub.com

This is a very cool solution, you change a small bit on your file’s url (instead of usingraw.github.com/… you use rawgithub.com/… ) and the file is delivered to you with the correct content type.
Awesome! But wait, there is a catch… the author of Rawgithub.com states:
Use this for testing and for sharing demo code with friends, but don’t use it for anything production-related. It’s slow, it might break from time to time, and it’s intended as a convenience for development, not free static hosting.
So, testing / development: cool, production: not cool.

And that is when it hit me, for some cases, doing what this service is doing for us, is really, actually, super easy, so I went ahead and created a small npm module, called “rawhub“.

Offline solution: rawhub

This is a node.js only solution, at least for now. What this module does, is simply download the resource from raw.github.com into a local folder on your server and then serve it from there.

Usage

On node, you setup the express middleware like this:

app.use(rawhub.setUp({folder: '/rawhub'}));

On your front-end, you change:

This: https://raw.github.com/user/repo/master/filename.js
For this: http://myserver.com/[FOLDERNAME]/user/repo/master/filename.js

Lets see a quick example of use

On the node.js side of things:

var express = require("express");
var rawhub = require("rawhub");
var app = express();

app.use(rawhub.setUp({folder: '/rawhub'}));
app.listen(3000);

That is a very simple express app, and it’s using rawhub. The setUp method is createing the middleware and the folder option is so rawhub knows which urls are meant to actually be fromraw.github.com.
That’s it, now on every request, rawhub will query github to get the file and will return it to you with the correct content type header.

On the HTML side of things:

<html>
  <head>
   <script src="/rawhub/user/repo/master/filename.js"></script>
<!-- ... -->

The change on the front-end is very simple, just treat the resource as if it was local on the folder you configure when setting up the middleware, and that’s it.

Other options

Doing a request to github on every request your site gets, can be a little too much, and it’ll add to your site’s loading time, so there is a cache option:

app.use(rawhub.setUp({
  folder: '/rawhub',
  cache: {
    folder: '/cache',
    ttl: 100
   }
}));

Now, with the above code, we’re telling rawhub to download and save the files from raw.github.com into ourproject/cache for 100 seconds.

And that’s it!

At least for now, this module was created in 2 hours, so there is probably a lot of room for improvement, I just hope someone can find it useful.

github raw user content

BASH COMMAND LINE WITH VIM AND EMACS MODE SHORTCUTS

BASH Command line Editing with Vim and EMACS Mode shortcuts options

This post is not directly related to programming, but I think that many developers can benefit from a few tips for the command line, since linux in it’s many flavours is widely used by developers out there.

So anyways…, as you may or may not know, I’m a big fan of what I like to call efficiency focused text editors, you may know them by the names of VIM and Emacs (there might be others, but those two are my favorites).
Even though they have different approaches to editing text on an efficient way, the main idea is the same: you don’t need to move your hands out of the “writing position” to achieve things like moving around the document, copy&pasting, selecting text, etc, etc.

If you’re like me, a fan of either one of them, you’ll be happy to know that you can do similar things on your linux command line. Yes, you read correctly: Bash has an emacs and a Vi mode (VI not VIM, almost the same)!

Emacs mode cheat sheet

This is the best one, simply because it’s the default mode for Bash. That’s right, out of the box, Bash allows you to move around your command line using Emacs commands.

For the complete cheat sheet, click here (credit goes to Peteris Krumins from http://www.catonmat.net).

Here are some examples of what you might do on your command line with it’s default mode:

Navigation

Moving around the line is as simple as it is on Emacs. Lets say you have the following command already typed in:

  %user>ls etc/apache2 _

You probably forgot the initial “/” on your path, so going back is as simple as hitting M-b twice!
Say that you now changed your mind, and decided that you want to see the content of your .shhfolder:

  %user>ls _etc/apache2 

Just hit C-k and write your new path!

  %user>ls ~/.ssh

Completition

Yes, on Bash you already have tab completition, but the one provided by the emacs mode is a bit more powerful:

Want to autocomplete an environment variable’s name? Hit C-x $
Want to autocomplete a hostname? Hit C-x @

You also have the usual completition commands that are available using the tab key:

Complete filename: Hit C-x /
Complete command name: Hit C-x !

Command repetition

One final note about the emacs mode: You can repeat the same command as many times as you wish the same way you would on your Emacs: M-[NUMBER] (being [NUMBER] the number of times you want to repeat your command).
For example, say your accidentally wrote everything in caps:

  %user>CAT /ETC/APACHE2/HTTP.CONF _

Just hit M-5 then M-b and you’re at the begining of the line, then hit: M-5 then M-l and it’s all lowecased!

Vi mode cheat sheet and shortcuts

Bash edit command line in vim / Vi editor,

The Vi mode for our bash is a very powerful mode too, and setting it up is not difficult at all, all you have to do is execute the following bash vi commands:

  %> set -o vi

You can add it to your .bashrc file so, everytime you open a new terminal window, it’ll auto-set the Vi mode.

For the complete cheat sheet, click here (credit goes, again, to Peteris Krumins from http://www.catonmat.net).

 

Here are some examples of what you might do on your command line with the Vi mode:

Navigation

Just like on the previous mode, moving around your command line using your Vi mode is as simple as it is to move around vi.
Lets use the same example:

  %user>ls etc/apache2 _

You probably forgot the initial “/” on your path, so going back is as simple as hitting ESC then b 3 times, that’s it, you’re at the start of etc.
Say that you now changed your mind, and decided that you want to see the content of your **.shh* folder:

  %user>ls _etc/apache2 

Just hit ESC again to enter command mode, and hit D, it’ll erase the line from there on, and you can now type in the new path. Easy!

That takes care of going back and forward, but what about up and down, how does that translate?
Hitting k and j on your command line, while on command mode, lets you navigate the command history.

bash vi mode indicator.

Command editing

Here is an example of something I found particularily interesting: Say you wrote a long and complex command, something like finding large files and creating a list with it’s names:

%>  find / -type f -size +20000k -exec ls -lh {} \; | awk ‘{ print $9 “:  $5 }’ > filelist.txt _

Once you’re done, you realize that you want to change some things around… , this mode allows you to change it easily, just hit ESC to enter command mode and then press v. TA-DA! You’re inside Vim (or Vi), able to edit your entire command as you wish.
When you’re done just save and quit, the new command will be executed automatically for you. Cool, uh?

To sum things up

This was a basic introduction to what you can do on your command line, as you’ll see on the cheat sheets available for download there are many more things to do. I encorage you to check them out, since the examples provided here are just the tip of the iceberg (trust me!).

I hope this helps you be a bit more efficient when working with it, I know it did for me!

bash command line editing cheat sheet
bash command line editing shortcuts
bash command line substitution
bash command line arguments
set show-mode-in-prompt on
bash vi mode key bindings

Javascript: you’re doing it wrong. JS limitations, Disadvantages over Java

Javascript: you’re doing it wrong. JS limitations, Disadvantages over Java

I’ve probably heard this a thouthand times already: “Javascript sucks! It has no classes, no inheritance, you have to fake all of it into the language…“.
If you’re also a web developer you either think that or thought that at some point of your learning process (I know I did), the way I see it, we all go through the following steps regarding Javascript:

  1. First, we look at it, and think “Meh, I guess I can use it and add some effects to my site..”
  2. Then when we start realizing the potential of the lenguage, we go out and try to fake concepts like classes, inheritance and whatnot into the language when creating some big application. By the time you finish your app, you probably hate the language since it “forced” you into adding all those extra needed things.
  3. And finally…we see the light: Javascript doesn’t need classes and all of those OOP concepts you love so much, it’s perfectly fine without them, and you end up loving the language.

So: What IS the deal with JavaScript?

First of all, Javascript is, as you may know by now, not a class oriented language, it is actually aprototype oriented language. This means that even though we don’t have the normal constructs we’re so used to having on our other OOP languages (such as JAVA, C++, etc) we are still able to define and reuse behavior through something called prototyping.

What is prototyping?

Prototyping is the ability to link two objects at runtime, giving the second one access to the methods and attributes of the first one (the prototype).
In javascript, every object has a property called prototype which allows them to be linked with one other object. Through this relationship, we can extend the behavior of our objects and, you guessed it, reuse code.

Lets take a look at a simple prototyping example in JS:

function parentObjectConstructor()
{ 
  this.name = "Object";
  this.one =  1;
  this.two =  2 
}

function childObjectConstructor() { 
    this.three =  3 
}
childObjectConstructor.prototype = new parentObjectConstructor();
childObjectConstructor.prototype.constructor = childObjectConstructor;

var childObject = new childObjectConstructor();
var parent = new parentObjectConstructor();

childObject.name = "Child";
console.debug(childObject.two) //Has number 2
console.debug(childObject.three) // Has number 3
console.debug(childObject.name) //Has string "Child"
console.debug(parent.name ) //Has the string "Object"

Pretty straight forward, uh?
Yes, prototyping is pretty cool, but that’s not the only cool thing Javascript has.

Lets talk about functions!

So, functions are actually pretty big in javascript, they’re something called first class, meaning that functions are objects themselves. They have attributes and methods, they can be assigned and passed as attributes to other functions. This is not something unique to javascript though, functional programming languages have this concept of higher order functions (i.e: lisp, clojure, etc).

In particular, with javascript you can do things like:

function myfunc(callback) {
   //Do some magic inside this functions
   callback(); //Call the function passed as parameter (awesome!)
}

//We call our function "myfunc" and pass another function as a callback.
myfunc(function() {
   //Do some more magic inside this function
});

//This time, we call "myfunc" again, reusing it's logic, but the callback is different...
myfunc(function() {
   //Do something completely different on this callback!
});

Another important concept related to functions is that of closures. Inside of your function definition, you can actually define other function, when you do that, a lexical closure is created, which relates the lexical scope of the outter function, including any constant, local variables and attributes values to the inner state of each of the inner function objects created.
Simply put, each inner function’s scope, includes the local variables, constants and attributes of the outter function.
This is specially fun if you return one of your inner functions, since they will still have access to the entire scope when called.

Here is an example of that same case, taken from Wikipedia:

function displayClosure() {
    var count = 0;
    return function () {
        return ++count;
    };
}
var inc = displayClosure();
inc(); // returns 1
inc(); // returns 2
inc(); // returns 3

To sum things up

Javascript is an incredibly powerfull and fun to use programming language, you just have to use it the way it was design to be used, not in the way you use JAVA (duh!).

Learn about prototyping, read about functional programming with javascript, and stop complaning about the fact that this wonderfull language doesn’t have things that it actually does not need.

Oh and don’t forget: Have fun while learning!