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');
});