Skip to content

Commit

Permalink
feat(lib): add datbase wrapper
Browse files Browse the repository at this point in the history
Signed-off-by: Hans Kristian Flaatten <hans.kristian.flaatten@dnt.no>
  • Loading branch information
Hans Kristian Flaatten committed Apr 22, 2016
1 parent 13e65a7 commit a22165d
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

const mongoose = require('mongoose');

if (mongoose.connection._hasOpened) {
module.exports = mongoose;
} else {
let mongoUri = process.env.MONGO_URI;

if (typeof mongoUri === 'undefined' || !mongoUri) {
if (!process.env.MONGO_DB) {
throw new Error('Environment variable "MONGO_DB" is undefined');
}

const addr = process.env.MONGO_PORT_27017_TCP_ADDR;
const port = process.env.MONGO_PORT_27017_TCP_PORT;
const db = process.env.MONGO_DB;

mongoUri = `mongodb://${addr}:${port}/${db}`;
}

module.exports = mongoose.connect(mongoUri);
module.exports.connection.on('error', err => {
throw err;
});
}

0 comments on commit a22165d

Please sign in to comment.