native-mongo-util
Advanced tools
Comparing version 1.0.8 to 2.0.0
186
index.js
@@ -5,42 +5,166 @@ const Log = require('lil-logger').getLogger(__filename); | ||
const Promise = require('bluebird'); | ||
const { MongoClient } = require('mongodb'); | ||
const mongodbURL = process.env.MONGO_URL || 'mongodb://localhost/test'; | ||
const { MongoClient, ObjectId } = require('mongodb'); | ||
const assert = require('assert'); | ||
const MONGO_URL = process.env.MONGO_URL || 'mongodb://localhost/test'; | ||
let _client; | ||
let _db; | ||
let isConnecting = false; | ||
exports.getDB = async function() { | ||
if (isConnecting) { | ||
Log.debug({ msg: 'connecting to DB' }); | ||
/** | ||
* Class to create native Mongo connection | ||
* @class Connection | ||
*/ | ||
class Connection { | ||
/** | ||
* Creates an instance of Connection. | ||
* @param {String} mongoURL - MongoDB url string | ||
* @memberof Connection | ||
*/ | ||
constructor(mongoURL) { | ||
assert(mongoURL); | ||
this._mongoURL = mongoURL; | ||
this._client = null; | ||
this._db = null; | ||
this._isConnecting = false; | ||
await sleep(2000); | ||
/** | ||
* Returns mongo collection for the given `collectionName` | ||
* | ||
* @public | ||
* @param {String} collectionName - Name of collection | ||
* @returns {Collection} - Mongo Collection instance | ||
*/ | ||
this.getCollection = memoize(collectionName => { | ||
this.checkAndThrowDBNotConnectedError(); | ||
return this._db.collection(collectionName); | ||
}); | ||
} | ||
if (!_client) { | ||
isConnecting = true; | ||
_client = await MongoClient.connect( | ||
mongodbURL, | ||
{ | ||
promiseLibrary: Promise, | ||
loggerLevel: 'error' | ||
} | ||
); | ||
_db = _client.db(); | ||
Log.debug({ msg: `DB connected: ${exports.getDBName()}` }); | ||
isConnecting = false; | ||
/** | ||
* Throw db not connected error | ||
* @memberof Connection | ||
* @private | ||
*/ | ||
checkAndThrowDBNotConnectedError() { | ||
if (!this._db) { | ||
throw new Error(`Not connected: ${this._mongoURL}. Call \`connect()\` method first.`); | ||
} | ||
} | ||
return _db; | ||
/** | ||
* Connects to mongodb for the provided `mongoURL` for this connection instance | ||
* @public | ||
* @returns {Promise<DB>} - Mongodb DB instance. | ||
* @memberof Connection | ||
*/ | ||
async connect() { | ||
if (this.isConnecting) { | ||
Log.debug({ msg: 'connecting to DB' }); | ||
await sleep(2000); | ||
} | ||
if (!this._client) { | ||
this.isConnecting = true; | ||
this._client = await MongoClient.connect( | ||
this._mongoURL, | ||
{ | ||
promiseLibrary: Promise, | ||
loggerLevel: 'error', | ||
useNewUrlParser: true | ||
} | ||
); | ||
this._db = this._client.db(); | ||
Log.debug({ msg: `DB connected: ${exports.getDBName()}` }); | ||
this.isConnecting = false; | ||
} | ||
return this._db; | ||
} | ||
/** | ||
* Returns Mongodb DB class instance of the connected db | ||
* | ||
* @public | ||
* @returns {DB} - Mongodb DB instance. | ||
* @memberof Connection | ||
*/ | ||
getDB() { | ||
this.checkAndThrowDBNotConnectedError(); | ||
return this._db; | ||
} | ||
/** | ||
* Returns connected db name | ||
* | ||
* @public | ||
* @returns {String} - Mongodb DB name | ||
* @memberof Connection | ||
*/ | ||
getDBName() { | ||
this.checkAndThrowDBNotConnectedError(); | ||
return this._db.databaseName; | ||
} | ||
/** | ||
* Returns `MongoClient` instance after calling `connect()` method of current `Connection` instance | ||
* | ||
* @public | ||
* @returns {Promise<MongoClient>} - MongoClient instance. | ||
* @memberof Connection | ||
*/ | ||
async getClient() { | ||
await this.connect(); | ||
return this._client; | ||
} | ||
} | ||
/** | ||
* Function will create & return new `Connection` instance. | ||
* @param {String} mongoURL - Valid mongodb connection string | ||
* @returns {Connection} - Connection instance | ||
*/ | ||
exports.newConnection = mongoURL => new Connection(mongoURL); | ||
let _defaultConnection = null; | ||
/** | ||
* Connects to mongodb instance, using `MONGO_URL` env var. | ||
* @returns {Promise<DB>} - Mongodb DB instance. | ||
*/ | ||
exports.connect = () => { | ||
if (_defaultConnection) { | ||
throw new Error(`Already connected to ${_defaultConnection.getDBName()}, Try \`newConnection()\` instead.`); | ||
} | ||
_defaultConnection = new Connection(MONGO_URL); | ||
return _defaultConnection.connect(); | ||
}; | ||
exports.getClient = async function() { | ||
await exports.getDB(); | ||
return _client; | ||
exports.getDB = () => { | ||
console.log('native-mongo-util: exports.getDB() is deprecated. Use exports.connect()'); | ||
return exports.connect(); | ||
}; | ||
exports.getDBName = () => _db.databaseName; | ||
/** | ||
* Returns `MongoClient` instance after calling `connect()` method | ||
* @returns {Promise<MongoClient>} - MongoClient instance. | ||
*/ | ||
exports.getClient = () => _defaultConnection.getClient(); | ||
exports.getCollection = memoize(collectionName => _db.collection(collectionName)); | ||
/** | ||
* Returns connected DB name. | ||
* @returns {String} - DB name. | ||
*/ | ||
exports.getDBName = () => _defaultConnection.getDBName(); | ||
exports.getDB().catch(e => { | ||
Log.error({ msg: 'Error occurred while connecting db', error: e }); | ||
process.exit(1); | ||
}); | ||
/** | ||
* Returns mongo collection for the given `collectionName` | ||
* | ||
* @param {String} collectionName - Name of collection | ||
* @returns {Collection} - Mongo Collection instance | ||
*/ | ||
exports.getCollection = collectionName => _defaultConnection.getCollection(collectionName); | ||
/** | ||
* Exporting mongodb `ObjectId` class. | ||
*/ | ||
exports.ObjectId = ObjectId; |
{ | ||
"name": "native-mongo-util", | ||
"version": "1.0.8", | ||
"version": "2.0.0", | ||
"description": "", | ||
@@ -30,11 +30,12 @@ "main": "index.js", | ||
"devDependencies": { | ||
"ava": "^0.25.0", | ||
"ava": "^1.2.1", | ||
"eslint": "^5.7.0", | ||
"eslint-config-lil": "^1.0.4", | ||
"eslint-config-prettier": "^3.1.0", | ||
"eslint-config-xo-space": "^0.20.0", | ||
"eslint-config-prettier": "^4.1.0", | ||
"eslint-config-xo-space": "^0.21.0", | ||
"eslint-plugin-prettier": "^3.0.0", | ||
"nodemon": "^1.18.4", | ||
"prettier": "^1.14.3" | ||
"prettier": "^1.14.3", | ||
"event-stream": ">=4.0.0" | ||
} | ||
} |
# native-mongo-util | ||
native mongo connection util | ||
Utility package to connect multiple mongo databases. | ||
## Usage | ||
https://travis-ci.org/saggiyogesh/native-mongo-util.svg?branch=master | ||
- Connect single db by configuring mongdb url in `MONGO_URL` env var. | ||
``` | ||
export MONGO_URL=mongodb://localhost/test | ||
``` | ||
Code to connect the above db & get mongo collection instance. | ||
```javascript | ||
const { connect, getCollection } = require('native-mongo-util'); | ||
(async () => { | ||
try { | ||
await connect(); // connect to db | ||
const userCollection = getCollection('user'); | ||
const allUsers = userCollection.find().toArray(); | ||
console.log(allUsers); | ||
} catch (err) { | ||
console.log('Error ocurred while connecting DB', err); | ||
throw err; | ||
} | ||
})(); | ||
``` | ||
- Connecting other mongo db | ||
```javascript | ||
const { newConnection } = require('native-mongo-util'); | ||
(async () => { | ||
try { | ||
const mongoURL = 'mongodb://localhost/someOtherDB'; | ||
const connection = newConnection(mongoURL); | ||
await connection.connect(); // connect to someOtherDB | ||
const studentsCollection = connection.getCollection('students'); // get students collection from someOtherDB connection. | ||
const allUsers = studentsCollection.find().toArray(); | ||
console.log(allUsers); | ||
} catch (err) { | ||
console.log('Error ocurred while connecting DB', err); | ||
throw err; | ||
} | ||
})(); | ||
``` | ||
## API | ||
- `exports.newConnection(mongoURL)` Function will create & return new `Connection` class instance. `mongoURL` is valid mongodb connection string. | ||
- `async exports.connect()` Async function that connects to mongodb, using `MONGO_URL` env var. Returns Mongodb `DB` class instance | ||
- `exports.getCollection(collectionName)` Returns Mongodb collection (`Collection` instance) for `collectionName`. | ||
- `async exports.getClient()` Returns Mongodb `MongoClient` class instance | ||
- `exports.getDBName()` Returns connected mongodb name | ||
- Class **Connection** methods | ||
- `constructor(mongoURL)` Valid mongodb connection string | ||
- `async connect()` Async method connects to mongodb, using `mongoURL` for the same instance. Returns Mongodb `DB` class instance | ||
- `getCollection(collectionName)` Returns mongodb collection. | ||
- `getDBName()` Returns db name | ||
- `async getClient()` Returns Mongodb `MongoClient` instance. | ||
[![Build Status](https://travis-ci.org/saggiyogesh/native-mongo-util.svg?branch=master)](https://travis-ci.org/saggiyogesh/native-mongo-util) |
32
test.js
import test from 'ava'; | ||
const { getDB, getDBName, getCollection } = require('./'); | ||
test('check connection with mongodb', async t => { | ||
await getDB(); | ||
const { getDBName, connect, getCollection, newConnection } = require('./'); | ||
test.serial('check connection with mongodb', async t => { | ||
await connect(); | ||
const dbName = getDBName(); | ||
t.is(dbName, 'test'); | ||
}); | ||
test.serial('fetch all records from a collection', async t => { | ||
const a = await getCollection('testCol') | ||
.find() | ||
.toArray(); | ||
t.is(a.length, 0); | ||
}); | ||
test.serial('another mongo connection', async t => { | ||
const mongoURL = 'mongodb://localhost/someDB'; | ||
const connection = newConnection(mongoURL); | ||
await connection.connect(); | ||
const dbName = connection.getDBName(); | ||
t.is(dbName, 'someDB'); | ||
const a = await connection | ||
.getCollection('testCol') | ||
.find() | ||
.toArray(); | ||
t.is(a.length, 0); | ||
}); |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
8954
174
70
9