ActiveRecord for Node.js

After learning Ruby on Rails (at least to some degree) I got into Node.js development. After developing a web app purely in Javascript in order to learn how to work with Node.js and socket.io I quickly found out that I’d actually have to go use CoffeeScript, simply because the OOP in JS was missing and I really didn’t want to mess with prototypes, etc.

CoffeeScript would support me in that it makes all the prototype-stuff in the background while I could write code as simple as class Human extends Creature. Besides that, it also has the awesome => operator as well as the do keyword, both of which I really missed after writing code in JavaScript that looks like this:

var array = ["Something", "Else", "Omg", "Test"]  
for (var i = 0; i < array.length; i++) {  
    var caption = array[i]
    $('ul').append($('<li>').text(caption).click(
        (function(caption) {
            return function() { alert(caption + ' clicked!') }
        })(caption)
    ))
}

Many of the JavaScript-developers out there probably recognize this pattern, as it’s being used quite often to say the least. It’s called a closure and is used especially in loops due to the fact that scopes in JavaScript are per-function, not per-block (Which is why two for-loops with a counter variable called i will throw a warning if you declare them in both loops with var i).

Basically that got me into rewriting the JavaScript code into CoffeeScript, where I also wanted to refactor everything because the previous code was sort of a rapidly created prototype of my web application. Since I was using simple fixtures that were implemented using basic JavaScript arrays and objects, I quickly decided to start using real database access this time. However, I quickly figured out that there is no ORM for Node.js that is still under active development. Because of that, I thought why not just create your own implementation of an ActiveRecord? So I started working on it just to figure out that it was easier than I previously thought it would be. Basically CoffeeScript surprised me with it’s awesomeness and similarity to Ruby. This made it even easier to write it very similar to it’s Ruby on Rails counterpart. For example, a simple User model may be written like this:

class User extends ActiveRecord  
    constructor: ->
        super
        @has 'email', is_optional: yes
        @has 'password', default: => "123#{@name}123"
        @has 'name'

So as you can see, it’s easy to read and very similar to the Ruby on Rails implementation, which was my main goal after all. I’ll keep working on it and when I have the time I’ll extract the ActiveRecord code from my web app and create a Github repository for it and submit it as a NPM package.