I just isolated an init function into a separate file. It only checks the database for the admin user here but in the future, I can register modules which are passed the app
and db
objects and I'll use async.each
to asynchronously load modules and run the init
method on each to start off the system. Once that they are all registered run init
on the express server.
server.js:
'use strict';
// Set the 'NODE_ENV' variable
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
process.env.PORT = process.env.PORT || 3000;
// Apparently __dirname doesn't work on Heroku
// @link http://stackoverflow.com/questions/17212624/deploy-nodejs-on-heroku-fails-serving-static-files-located-in-subfolders
process.env.PWD = process.cwd();
// Load the module dependencies
var mongoose = require('./server/config/mongoose'),
express = require('./server/config/express'),
init = require('./server/config/init');
// Create a new Mongoose connection instance
var db = mongoose();
// Create a new Express application instance
var app = express(db);
// Run the init this way in future refactor modules into separate folders.
init(app, db)
.then(function initialized() {
// Use the Express application instance to listen to the '3000' port
app.listen(process.env.PORT);
// Log the server status to the console
console.log('Server running at http://localhost:' + process.env.PORT + '/');
});
// Use the module.exports property to expose our Express application instance for external ussage
module.exports = app;
server/config/init.js:
'use strict';
var config = require('./config');
module.exports = function(app, db) {
return new Promise(function(resolve) {
var User = db.model('User');
User.findOne({ email: config.adminAccountEmail}, function(err, user) {
if (err) throw err;
if (!user) {
var newAdmin = new User({
email: config.adminAccountEmail,
password: config.adminAccountPassword,
roles: ['administrator', 'authenticated', 'anonymous']
});
newAdmin.save(function(err) {
if (err) throw err;
resolve();
})
} else {
resolve();
}
})
})
};
server/config/production.js:
'use strict';
/**
* Set the 'production' environment configuration object
* @link http://docs.mongolab.com/migrating/
*/
module.exports = {
db: process.env.MONGODB_URI,
// set this to build
// dir: 'build/',
dir: 'client/',
fileDir: 'files/',
sessionSecret: process.env.SESSION_SECRET || 'MEAN',
adminAccountEmail: process.env.ADMIN_ACCOUNT_EMAIL || 'admin@simpleyachtjobs.com',
adminAccountPassword: process.env.ADMIN_ACCOUNT_PASSWORD || 'password'
}