Created
December 14, 2018 15:30
-
-
Save roelvan/1d6b23dba1d9aa1de7ae1cf71ddb890f to your computer and use it in GitHub Desktop.
This file contains 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
const { MongoClient } = require('mongodb'); | |
const { promisify } = require('es6-promisify'); | |
let _connection; | |
const connect = () => { | |
if (!process.env.MONGO_URL) { | |
throw new Error(`Environment variable MONGO_URL must be set to use API.`); | |
} | |
return promisify(MongoClient.connect)(process.env.MONGO_URL, { | |
useNewUrlParser: true | |
}); | |
}; | |
/** | |
* Returns a promise of a `db` object. Subsequent calls to this function returns | |
* the **same** promise, so it can be called any number of times without setting | |
* up a new connection every time. | |
*/ | |
const connection = () => { | |
if (!_connection) { | |
_connection = connect(); | |
} | |
return _connection; | |
}; | |
/** | |
* Returns a ready-to-use `collection` object from MongoDB. | |
* Usage: | |
* (await getCollection('users')).find().toArray().then( ... ) | |
*/ | |
async function getCollection(collectionName) { | |
const db = (await connection()).db(process.env.MONGO_DB_NAME); | |
return db.collection(collectionName); | |
} | |
module.exports = { | |
connection, | |
getCollection | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment