Skip to content

Colin Webb

Aggregation Services in Node.js

My previous blog post talked about building Aggregation Services using Play-JSON. In it, I mentioned that Aggregation Services using JavaScript might be quite nice. As JSON is native to JavaScript, you might expect manipulating JSON in JavaScript to be incredibly simple. And you would be correct!

Below is the same functionality as last time, but with Node.js. To recap, we fetch an article a1, which contains a list of products ids [s1, s2, s3]. We load the article, and then have to fetch all the products it contains.

var express = require('express'),
    request = require('request'),
    async = require('async'),
    app = express();

// where our json data lives
var data = {
	"s3": "",
	"s2": "",
	"s1": "",
	"a1": ""

var fetchProduct = function(item, cb) {
	request.get(data[item], {json:true}, function(error, response, body){
		cb(null, body);

app.get('/', function(req, res){
	request.get(data['a1'], {json:true}, function(error, response, body){['product_list'], fetchProduct, function(err, results){
			// mutate all the state!!
			body['product_list'] = results.filter(function(n){ return n }); 	


Having worked a lot with Scala and Clojure recently, I keep forgetting that one can actually mutate variables! If the service is kept relatively small, the mutation should be forgiveable.

This isn't production-ready code. Error handling is missing for the first HTTP request, and if fetchProduct returns an error, erroring products are filtered out. Hopefully though, the code gives a flavour of what an Aggregation service written in Node.js would look like.