Skip to content

Exit on startup when MongoDB connection fails #223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const http = require('http');
const compress = require('compression');
const cors = require('cors');

const db = require('./models/db')(process.env.spec);
const db = require('./models/db')
const index = require('./routes/index');
const api = require('./routes/api');
const stats = require('./routes/stats');
Expand All @@ -16,7 +16,6 @@ const store = require('./store');

const app = express();
const server = http.createServer(app);
require('./sockets.js')(server);

// view engine setup
app.set('views', path.join(__dirname, '.viewsMin'));
Expand Down Expand Up @@ -53,7 +52,9 @@ app.use((err, req, res, next) => {

// Load and initialize generators before starting server
(async() => {
await db(process.env.spec);
await require('./loadGenerators')();
require('./sockets.js')(server);
startServer();
})();

Expand Down
25 changes: 16 additions & 9 deletions models/db.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
const mongoose = require('mongoose');
const settings = require('../settings');

module.exports = testEnv => {
module.exports = async testEnv => {
const dbName = settings.db + (testEnv ? '-test' : '');

mongoose.connect('mongodb://localhost/' + dbName, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
mongoose.set('useCreateIndex', true);

const db = mongoose.connection;
db.on('connecting', console.log.bind(console, '[database] Connecting to MongoDB...'));
db.on('connected', console.log.bind(console, '[database] Connected to MongoDB.'));
db.on('error', console.error.bind(console, '[database] Error occured while connecting to MongoDB.'));
db.on('error', console.error.bind(console, '[database] Error occured in MongoDB connection.'));

try {
await mongoose.connect('mongodb://localhost/' + dbName, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
} catch (err) {
console.error('[database] Error occured while connecting to MongoDB. Is it running?');
process.exit(1);
}

mongoose.set('useCreateIndex', true);
};