0
\$\begingroup\$

This is my app.js:

'use strict';
global.config = require('./config/environment/config');
global.i18n = require('./config/locales/config');

var express = require('express');
var app = express();

app.locals = global.config;

var passport = require('passport');
var session = require('express-session');
var load = require('express-load');
var flash = require('express-flash');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

app.set('views', path.join(__dirname, 'views'))
    .set('view engine', global.config.site.html.engine)
    .set('port', process.env.PORT || 3000)
    .set('env', process.env.NODE_ENV || 'development')
    .set('ip', process.env.IP || "0.0.0.0")

app.use(favicon(__dirname + '/assets/favicon.ico'))
    .use(logger('dev'))
    .use(bodyParser.json())
    .use(bodyParser.urlencoded({ extended: false }))
    .use(flash())
    .use(cookieParser())
    .use(express.static(path.join(__dirname, 'assets')))
    .use(session({ secret: 'keyboard cat' }))
    .use(passport.initialize())
    .use(passport.session());


var middlewares = require('./middlewares/config')(app);

load('models')
    .then('controllers')
    .then('routes')
    .into(app);

var prototypes = require('./helpers/prototypes');

mongoose.connect('mongodb://' + global.config.db.credentials + '@' + global.config.db.url + '/' + global.config.db.name, function(req, res) {
    console.log('db ok');
});

module.exports = app;

One aspect that annoys me is that I would prefer to have all the require() calls together. However, if I move middlewares and prototypes before app.set(), the code will break. Is there a better way to organize this code?

\$\endgroup\$
1
\$\begingroup\$

You can always move the require() call for middlewares up. You're not doing anything with the returned value from calling it on app.

var middlewares = require('./middlewares/config');

app.set(.....)

app.use(.....)

middlewares(app)

I'm assuming prototypes does some hacks with the global namespace. If so, then there's not much you can do about it. That's not really good practice though.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.