Clean code.

This commit is contained in:
2020-09-06 19:36:58 +02:00
parent dc79b7bc0e
commit 29411d3c87
5 changed files with 76 additions and 56 deletions

View File

@@ -0,0 +1,52 @@
const mongodb = require('mongodb');
const assert = require('assert');
const configuration = require('../configuration');
const mongoConfig = configuration.database;
class MongoClient {
constructor() {
mongodb.MongoClient.connect(mongoConfig.url, (error, client) => {
assert.equal(null, error, `Unable to connect to mongodb: ${error}.`);
console.log('Connected successfuly to mongodb');
this.db = client.db(mongoConfig.database);
});
}
find(collectionName, query, callback) {
this.db.collection(collectionName).find(query).toArray()
.then(results => {
console.log(`Entities ${collectionName} founded.`);
callback(results);
})
.catch(error => console.error(error));
}
insert(collectionName, entity, callback) {
this.db.collection(collectionName).insert(entity, (error, result) => {
assert.equal(null, error, `Unable to insert ${collectionName} entity: ${error}.`);
console.log(`Entity ${collectionName} inserted.`);
// Return only the inserted document.
callback(result.ops[0]);
});
}
update(collectionName, entity, callback) {
this.db.collection(collectionName).save(entity, (error) => {
assert.equal(null, error, `Unable to update ${collectionName} entity: ${error}.`);
console.log(`Entity ${collectionName} updated.`);
callback();
});
}
delete(collectionName, entityId, callback) {
this.db.collection(collectionName).deleteOne({_id: mongodb.ObjectId(entityId)}, (error, result) => {
assert.equal(null, error, `Unable to delete ${collectionName} entity with id ${entityId}: ${error}.`);
console.log(`Entity ${collectionName} with id ${entityId} deleted.`);
callback();
});
}
}
const mongoClient = new MongoClient();
module.exports = mongoClient;