5

I am using node Express 4.0 for my web server and rest api. I am using content negotiation to server multiple types of data and handling versioning of the rest API. However, my interface is starting to be very cluttered. Below i have a very simple example to illustrate how i use content negotiation (but i have a lot more lines of codes in each accept header.

My question is, do any have experiences with large Express rest applications and how to structure the code to separate concerns between the HTTP part and the actual data handling to avoid very cluttered app.get(), app.post(), etc. functions and how to keep a good overview of the entire application?

'use strict';

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

var data = [
    { id: 0, title: 'This is content 0'},
    { id: 1, title: 'This is content 1'},
    { id: 2, title: 'This is content 2'},
    { id: 3, title: 'This is content 3'}
];

app.get('/data', function(req, res) {

    res.format({
        'application/vnd.mydata.ids.v1.0+json': function() {
            var ids = data.map(function(d) { return d.id; });
            res.json(ids);
        },
        'application/vnd.mydata.ids.v1.0+html': function() {
            var ids = data.map(function(d) { return '<p>' + d.id + '</p>'; });
            res.send(ids.join(''));
        },
        'application/vnd.mydata.all.v1.0+json': function() {
            res.json(data);
        },
        'application/vnd.mydata.all.v1.0+html': function() {
            var all = data.map(function(d) { return '<p>' + d.id + ': ' + d.title + '</p>'; });
            res.send(all.join(''));
        }
    });

});

app.listen(8080, function() {
    console.log('Server started');
});
aweis
  • 5,350
  • 4
  • 30
  • 46
  • possible duplicate of [How to separate routes on Node.js and Express 4?](http://stackoverflow.com/questions/23923365/how-to-separate-routes-on-node-js-and-express-4) – Matthew Bakaitis Feb 22 '15 at 02:51
  • Hi @MatthewBakaitis, that question is about using router and the middle-ware functionality to require routes from other files. I already use that, but my question is minded on separating code inside each single url destination because of an extensive use of accept headers inside each of them! – aweis Feb 22 '15 at 08:54

0 Answers0