Skip to content

Commit

Permalink
Class based (#1)
Browse files Browse the repository at this point in the history
* 2.0.0

* create class based objects

* ignore test file

* remove ops files now is in one class file

* fix incorrect file call

* avoid name collision

* avoid name collision and check data before open connection

* upgrade mongodb packages

* create check for config files

* rewrite test files

* adjust test

* adjust validation config

* add sinon as dev dependencies

* bugfix were call this before super

* create test for new db format

* upgrade mocha packages due security issues

* remove old files

* adjust db and test file for db

* test operations and adjust handle with insert

* crete test for collections and connections

* run test recursivily

* ignore coverage files

* add nyc package to coverage unit test

* write tests for find function

* adjust username for url generation in db

* refactoring operations

* WIP create integration test

* ignore coverage files

* improve test coverage before final release

* set new versions for node

* create integration cmd for integration test

* new configuration to a new version

* adjust style code and some name conflicts

* adjust some cases to integration test

* adjust unit test to avoid rejection and cover more scenarios

* adjust passwords and code climate keys

* adjust user and db name

* remove spread operator not supported by old versions

* update docs to version 2

* adjust to debug CI

* update travis pass

* adjust mongo users

* update mongo configuration

* fix travis.yml could be parsed

* adjust to accept query_params in url

* update our docs

* hotfix to avoid broken url

* 2.0.1
  • Loading branch information
flpms authored Jan 27, 2019
1 parent ffd8c14 commit 45d528f
Show file tree
Hide file tree
Showing 25 changed files with 4,172 additions and 624 deletions.
13 changes: 10 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -212,12 +212,19 @@ pip-log.txt
#Translations
*.mo

#Mr Developer
# Mr Developer
.mr.developer.cfg

# Node
node_modules/
config/
coverage/
.nyc_output/

# for project

test-index.js

# ignore coverage

.nyc_output/

coverage/
25 changes: 12 additions & 13 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
language: node_js
node_js:
- "10.15"
- "10.0"
- "8.15.0"
- "8.0.0"
- "7.0"
- "6.16.0"
- "6.0"
- "5.0"
- "4.9.1"
- "4.0"
- "4.1"
- "iojs"
- "6.0"
- "8.0"
- "8.15"
- "9.0"
- "10.0"
- "10.15"
- "11.0"
env:
global:
- CC_TEST_REPORTER_ID=18b4941291c81f7002e4ec5d7d38c9b3e31cf89f2393165e6bcf647c4a15b062
- MONGO_USER="travis"
- MONGO_PASS="test"
services:
- mongo mydb_test --eval 'db.addUser("travis", "test");'
- sleep 15
- mongodb
- sleep 15
- mongo mydb_test --eval 'db.createUser({user:"travis",pwd:"test",roles:["readWrite"]});'
addons:
apt:
sources:
Expand All @@ -31,5 +29,6 @@ before_script:
- ./cc-test-reporter before-build
script:
- npm test
- npm run test-integration
after_script:
- ./cc-test-reporter after-build -t lcov --debug --exit-code $TRAVIS_TEST_RESULT
56 changes: 40 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,64 @@
# Simple Connection - [![build status](https://secure.travis-ci.org/flpms/simple-connection.png)](http://travis-ci.org/flpms/simple-connection) [![Code Climate](https://codeclimate.com/github/flpms/simple-connection/badges/gpa.svg)](https://codeclimate.com/github/flpms/simple-connection)

I get some codes which I used in a project, and put into this repository.
Is a small implementation for access mongodb with native drives provided by mongodb.

Is a ES 6 ready.
A small implementation to use mongodb with native drives provided by mongodb, but with promises.

## Install

`npm install simple-connection --save`


## About config object

Configurantion object the you can build connection url the keys username and password are optional. Also you can send a `query_params` key to build connection url with more mongo parameters. In example you can found how to send configuration object and how to create instantion to use with simple-connection.

## Example

```` javascript

var DB = require('simple-connection');
const DB = require('simple-connection');

const CONFIG = {
"username": process.env.MONGO_USER,
"password": process.env.MONGO_PASS,
"server": "127.0.0.1",
"port": 27017,
"database_name": "exampleTest"
};

var db = DB.config({
"username": "",
"password": "#",
"server": "localhost",
"port": 27017,
"database_name": "exampleTest"
const db = new DB(CONFIG);
const collection = db.open('yourCollection');

// to insert many pass an array with objects
collection.insert({ data: 'to insert' }).then((success) => {
console.log(success);
}).catch((err) => {
console.log(err);
});

db.collection('yourCollection');
// Or if your prefer async/await
try {
const result = await collection.insert({ data: 'to insert' });
console.log(result);
} catch(error)
console.log(err);
};

collection.find({ data: 'to search' }).then((success) => {
console.log(success);
}).catch((err) => {
console.log(err);
});

db.find({your: 'search'}).then((success) => {
collection.update({ data: 'to search' }, { data: 'to update' }).then((success) => {
console.log(success);
}).catch((err) => {
console.log(err);
})
});

db.remove({your: 'search'}, options).then((success) => {
collection.remove({ data: 'to remove' }, options).then((success) => {
console.log(success);
}).catch((err) => {
console.log(err);
})
});

````
11 changes: 11 additions & 0 deletions lib/collections.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

const Operations = require('./operations');

class Collections extends Operations {
constructor(collectionName, dbConnection) {
return super(collectionName, dbConnection);
}
}

module.exports = Collections;
11 changes: 0 additions & 11 deletions lib/connect-db.js

This file was deleted.

21 changes: 21 additions & 0 deletions lib/connections.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

const MongoClient = require('mongodb').MongoClient;

class Connections {
constructor(url) {
this.url = url;
}

createConnection() {
this._connection = new Promise((resolve, reject) => {
MongoClient.connect(this.url, (err, db) => { err ? reject(err) : resolve(db) });
});
}

get connection() {
return this._connection;
}
}

module.exports = Connections;
68 changes: 43 additions & 25 deletions lib/db.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,53 @@
'use strict';

const ops = require('./ops');
const Connections = require('./connections');
const Collections = require('./collections');

let Collection = function(collectionName, config) {
class DB extends Connections {

if (!Object.keys(config).length) {
throw 'Don\'t have a DB config';
constructor(config) {
if (!config) {
throw new Error('connection configuration not defined');
}

let url = `mongodb://${config.server}:${config.port}/${config.database_name}`;

return {
insert: (data) => {
return ops.insert.call({ url: url, collectionName: collectionName }, data);
},
find: (data) => {
return ops.find.call({ url: url, collectionName: collectionName }, data);
},
remove: (data, options) => {
return ops.remove.apply({ url: url, collectionName: collectionName }, [data, options]);
},
update: (query, update, options) => {
return ops.update.apply({ url: url, collectionName: collectionName }, [query, update, options]);
}
const userAndPass = (username, password) => {
if(username && password) {
return `${username}:${password}@`;
}

if(username) {
return `${username}@`;
}

return '';
};
};

module.exports = (config) => {
return {
collection: (collectionName) => {
return (Collection(collectionName, config));
}
const url = `mongodb://${userAndPass(config.username, config.password)}${config.server}:${config.port}/${config.database_name}${(config.query_params || '')}`;

super(url);

this.config = config;

if (!this.validConfig) {
throw new Error('invalid connection configuration json');
}

return this;
}

open(collectionName) {
super.createConnection();
return new Collections(collectionName, super.connection);
}

get validConfig() {
if (this.config.hasOwnProperty('server') &&
this.config.hasOwnProperty('port') &&
this.config.hasOwnProperty('database_name')) {
return true;
}
}

}

module.exports = DB;
119 changes: 119 additions & 0 deletions lib/operations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
'use strict';

class Operations {

constructor(collectionName, connection) {
this.connection = connection;
this.collectionName = collectionName;
}

createPromise(cb) {
return new Promise(cb);
}

retriveCollection(db) {
return db.collection(this.collectionName);
}

checkForData(data) {
return !data || !Object.keys(data).length;
}

startOperations() {
return this.connection.then((db) => {
return this.createOperationObject.call(this, db);
});
}

createOperationObject(db) {
return {
collection: this.retriveCollection(db),
db: db
}
}

insert(data, options) {
return this.createPromise((resolve, reject) => {
if (this.checkForData(data)) {
reject('No data to insert');
}

const operations = this.startOperations();

operations.then((op) => {
const result = (err, res) => {
op.db.close();
return err ? reject(err) : resolve(res);
};

if (Array.isArray(data)) {
return op.collection.insertMany(data, options, result);
}

op.collection.insert(data, options, result);

}).catch(reject);
});
}

find(data, projection) {
return this.createPromise((resolve, reject) => {
if (this.checkForData(data)) {
return reject('No data to find');
}

const operations = this.startOperations();

operations.then((op) => {
op.collection
.find(data, projection ? projection : '')
.toArray((err, docs) => {
op.db.close();
return err ? reject(err) : resolve(docs);
});
}).catch(reject);
});
}

remove(data, options) {
return this.createPromise((resolve, reject) => {
if (this.checkForData(data)) {
return reject('No data to remove');
}

const operations = this.startOperations();

operations.then((op) => {
op.collection
.remove(data, options, (err, result) => {
op.db.close();
(err) ? reject(err) : resolve(result);
});
}).catch(reject);
});
}

update(query, update, options) {
return this.createPromise((resolve, reject) => {
if (this.checkForData(query)) {
return reject('No query to looking for');
}

if (this.checkForData(update)) {
return reject('No data to update');
}

const operations = this.startOperations();

operations.then((op) => {
op.collection
.update(query, update, options, (err, result) => {
op.db.close();
(err) ? reject(err) : resolve(result);
});
}).catch(reject);
});
}
}

module.exports = Operations;
Loading

0 comments on commit 45d528f

Please sign in to comment.