diff --git a/app.js b/app.js index 7140a80..f95024d 100644 --- a/app.js +++ b/app.js @@ -35,11 +35,36 @@ function initApp(config, callback) { } const app = new EventEmitter(); + app.address = null; app.express = express(); app.server = http.createServer(app.express); app.webservice = createClient(webserviceUrl); + loadMiddleware(app); + + // View engine + loadViewEngine(app, config); + + // Load routes + loadRoutes(app, config); + + // Error handling + loadErrorHandling(app, config, callback); +} + +// Get default configurations +function defaultConfig(config) { + if (typeof config.noindex !== 'boolean') { + config.noindex = true; + } + if (typeof config.readonly !== 'boolean') { + config.readonly = false; + } + return config; +} + +function loadMiddleware(app) { // Compression app.express.use(compression()); @@ -53,8 +78,9 @@ function initApp(config, callback) { app.express.use(bodyParser.urlencoded({ extended: true })); +} - // View engine +function loadViewEngine(app, config) { app.express.engine('html', hbs.express4({ extname: '.html', contentHelperName: 'content', @@ -89,10 +115,16 @@ function initApp(config, callback) { response.locals.host = request.hostname; next(); }); +} - // Load routes +function loadRoutes(app, config) { + // Because there's some overlap between the different routes, + // they have to be loaded in a specific order in order to avoid + // passing mongo the wrong id which would result in + // "ObjectID generation failed." errors (e.g. #277) require('./route/index')(app); require('./route/result/download')(app); + if (!config.readonly) { require('./route/new')(app); require('./route/task/delete')(app); @@ -101,12 +133,14 @@ function initApp(config, callback) { require('./route/task/ignore')(app); require('./route/task/unignore')(app); } + // Needs to be loaded after `/route/new` require('./route/task/index')(app); // Needs to be loaded after `/route/task/edit` require('./route/result/index')(app); +} - // Error handling +function loadErrorHandling(app, config, callback) { app.express.get('*', (request, response) => { response.status(404); response.render('404'); @@ -129,16 +163,4 @@ function initApp(config, callback) { app.address = `http://${address.address}:${address.port}`; callback(error, app); }); - -} - -// Get default configurations -function defaultConfig(config) { - if (typeof config.noindex !== 'boolean') { - config.noindex = true; - } - if (typeof config.readonly !== 'boolean') { - config.readonly = false; - } - return config; }