Created
January 24, 2019 14:47
-
-
Save bmorrisondev/fb6dc15d3880e54cbaa1c63b76cf3814 to your computer and use it in GitHub Desktop.
A mongoose connection helper script that builds a connection string from environment variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// env.test file: | |
// DB_HOST="localhost" | |
// DB_PORT="27017" | |
// DB_NAME="dbname" | |
// DB_USER="dbusername" | |
// DB_PASS="dbpassword" | |
require('custom-env').env(true) | |
const mongoose = require('mongoose') | |
exports.connect = async () => { | |
try { | |
let connectionString = await this.connectionString() | |
mongoose.connection.on('error', (err) => { | |
throw new Error(`Unable to connect to db: ${err.message}`) | |
}) | |
return await mongoose.connect(connectionString, { useNewUrlParser: true, useFindAndModify: false }) | |
} catch (err) { | |
throw new Error(`dbhelper.connect: ${err.message}`) | |
} | |
} | |
exports.connectionString = () => { | |
let connectionString = '' | |
try { | |
if (process.env.DB_PROTOCOL) { | |
connectionString += `${process.env.DB_PROTOCOL}://` | |
} else { | |
connectionString += `mongodb://` | |
} | |
if (process.env.DB_USER && process.env.DB_PASS) { | |
connectionString += `${process.env.DB_USER}:${process.env.DB_PASS}@` | |
} | |
connectionString += `${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}` | |
} catch (err) { | |
throw new Error(`dbhelper.connectionString: ${err.message}`) | |
} | |
return connectionString | |
} |
It is cleaner to use connection-string, which knows how to sanitize all the string segments properly.
Did you just hijack my gist to pitch your own library??? 🤣
If there is a better way to do something, I'm all for it 👍
const {ConnectionString} = require('connection-string');
const cs = new ConnectionString();
cs.setDefaults({
protocol: process.env.DB_PROTOCOL || 'mongodb',
user: process.env.DB_USER,
password: process.env.DB_PASS,
hosts: [
{name: process.env.DB_HOST, port: process.env.DB_PORT}
],
path: [process.env.DB_NAME]
});
// to generate the connection string:
const connection = cs.toString();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is cleaner to use connection-string, which knows how to sanitize all the string segments properly.