Skip to content

Instantly share code, notes, and snippets.

@jonathanmarvens
Created May 23, 2014 04:11
Show Gist options
  • Save jonathanmarvens/f226a7c1a2fcb021dce7 to your computer and use it in GitHub Desktop.
Save jonathanmarvens/f226a7c1a2fcb021dce7 to your computer and use it in GitHub Desktop.
I was just going through some old Node.js code, and I thought I'd share how I usually organize Express-based apps.
'use strict';
var
app,
appConfig,
cors,
express
;
appConfig = require('./app-config');
cors = require('cors');
express = require('express');
app = express();
app.set('_app.config', appConfig);
app.set(
'_app.helpers',
require('./app-helpers')
);
[
'method-override',
{
args: [
'dev'
],
name: 'morgan'
},
'compression',
'body-parser'
].forEach(function (middleware) {
var
_tmp00
;
if (typeof middleware === 'string') {
_tmp00 = middleware;
middleware = {
args: [],
name: _tmp00
};
}
if (middleware.func) {
app.use(
middleware.func.apply(null, middleware.args)
);
} else {
app.use(
require(middleware.name).apply(null, middleware.args)
);
}
});
app.use(
cors(appConfig.api.cors)
);
(function () {
var
appEndpointsDir,
routeObjects,
routePaths
;
appEndpointsDir = './endpoints';
routeObjects = [];
routePaths = {
ping: '/ping'
};
/**
* Test route.
*/
routeObjects.push({
action: function (request, response) {
response.send('PONG!');
},
method: 'get',
path: routePaths.ping
});
routeObjects.forEach(function (route) {
var
args,
routeAction,
routeMethod,
routeMiddleware
;
args = [];
routeAction = route.action ? route.action : null;
routeMethod = route.method ? route.method : 'all';
routeMiddleware = route.middleware ? route.middleware : null;
args.push(route.path);
if (routeMiddleware) {
args.push(routeMiddleware);
}
if (routeAction) {
if (typeof routeAction === 'function') {
routeAction = routeAction.bind(app);
} else if (typeof routeAction === 'string') {
routeAction = require(appEndpointsDir + routeAction)[routeMethod].bind(app);
}
args.push(routeAction);
}
app[routeMethod].apply(app, args);
});
}).call(this);
app.listen(appConfig.api.port, '127.0.0.1');
console.log('Server is now listening at: http://127.0.0.1:' + appConfig.api.port + '!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment