Using AngularJS and Node

I’ve been using angularjs the “Superheroic JavaScript MVW Framework” on a couple of my projects and I’ve become quite a fan. It really helps structure all the spidery browser side javascript that inevitably occurs when creating elegant user interfaces with the wow factor. Sure there’s a bit of a learning curve but well worth persevering.

Couple some client side angularjs services with a node.js server and you have a winning combination. I’m always suprised at how quickly I can develop using these technologies.

A common pattern I was finding myself applying was creating angularjs services using the $resource factory for common entities. Initially I created custom actions, but soon realised the default actions were normally quite suitable for most of what I needed.

It’s a bit repetitive

This pattern results in somewhat repetitive server side express endpoints. In order to improve things somewhat, I have created a node.js module called angular-resource.

I’ve written some documentation, but in summary if you have an angular service that looks like this:

var myServices = angular.module('myServices', ['ngResource'])

myServices.factory('Task', function($resource) {
  return $resource('api/tasks/:id', {
    id: "@_id"
  });
});

and you have a task implementation that looks like this:

var task = {};

task.get = function(req, res) {
  res.json({});
};

task.save = function(req, res) {
  res.send(200);
};

task.query = function(req, res) {
  res.json([]);
};

task.remove = function(req, res) {
  res.send(200);
};

module.exports = task;  

Then the following server code will create the necessary endpoints, either with or without middleware:

var angularRest = require('angular-rest'),
  express = require('express');

var app = express();

var middleware = function(req, res, next) {
  return next(req, res);
};

// without middleware
angularRest(app, '/api/1', 'task');

// with middleware
angularRest(app, '/api/2', 'task', middleware);

app.listen(3000);

Hopefully, you find that it simplifies things for you. Please let me know any feedback, and I always welcome useful pull requests.

(Thanks to gist-it for code snippets).