I am working on a web api on node.js using the Express3 framework and I would want my routing to look something like /v0.1/function.
Ideally, the routing should automatically load the specified version module by looking at the major and minor version number given in the url. My approach so far is:
app.use('/v:major.:minor', function(req) {
return require('./v' + req.params.major + '.' +
req.params.minor);
});
And in my ./v0.1/index.js:
module.exports = function() {
var express = require('express'),
app = express();
app.get('/test', function(req, res) {
res.json({ success: true });
});
return app;
}();
If I call /v0.1/test now, it somehow does not match the route (404), but app.get('/v:major.:minor', function(req, res) { /* ... */ }); is working just fine.
How can I achieve this?
I think you want app.all (http://expressjs.com/api.html#app.all)
This will make is accessible for all HTTP Verbs and still have the variable routing working.
I tested it and it seems to work.
Edited as per comment
app.all('/v:major.:minor/:endpoint', function(req, res, next) {
var version_handler = require('./v' + req.params.major + '.' + req.params.minor);
if (!req.params.endpoint in version_handler) // endpoint_isn't supported at this version, 404
version_handler[req.params.endpoint](req, res, next);
});
You have to use app.param(). From the example in express API :
app.param('id', /^\d+$/);
app.get('/user/:id', function(req, res){
res.send('user ' + req.params.id);
});
You must provide the regular expression for your parameter in URL, since major, minor both are non negative integers /^\d+$/ should be it for you.