nodejs express route config

We’ve currently been developing more nodejs services here at MetaTowers and as “We’re all about the metadata”™ why not use some to describe our endpoints!? Below is a simple example of what we came up with using express.

index.js


// Include express
var express = require('express');

// Define our routes and their methods
var routesConfig = {
    uri: '/',
    path: 'root',
    methods: ['get']
};
// Where are the files for the routes?
var routesDir = './routes/';

// expressstuff.js
var router = express.Router();
var app = express();
app.use('/1', router);

routesConfig.forEach(function(route) {
  var file;
  route.methods.forEach(function(method) {
    // The following constructs something similar to:
    // `router.get('/', function (req, res) {`
    // based on the routesConfig routes and methods
    router[method](route.uri, function(req, res) {
      try {
        file = require(routesDir + route.path);
      } catch (e) {
        // Automatically 404 if the `route.path` doesn't exist
        console.error(e);
        require(routesDir + 'errors')['404'](req, res, route.path);
        return;
      }

      if (!file[method]) {
        // Automatically 501 if the `route.method` requested does not exist
        console.error(method + ' not implemented for ' + route.path);
        require(routesDir + 'errors')['501'](req, res, route.path, method);
        return;
      }

      // Serve the method from the file (see root.js below)
      file[method](req, res, db);
    });
  });
});

// Start the server
app.listen('8080', function() {
  console.info('Server listening on ' + config.port);
});

/routes/root.js

exports.get = function(req, res) {
  res.send({
    greeting: {
      type: 'informal',
      value: 'Hello'
    },
    object: {
      type: 'orbital',
      value: 'world'
    }
  });
};

/routes/errors.js

exports['404'] = function(req, res, path) {
  res.status(404).send({
    statusCode: 404,
    error: path + ' not found'
  });
};

exports['501'] = function(req, res, path, method) {
  res.status(501).send({
    statusCode: 501,
    error: method + ' not implemented'
  });
};

If you enjoyed the read, drop us a comment below or share the article, follow us on Twitter or subscribe to our #MetaBeers newsletter. Before you go, grab a PDF of the article, and let us know if it’s time we worked together.

blog comments powered by Disqus