Skip to content

Commit

Permalink
Ok v0.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexandre Germain committed Oct 17, 2017
1 parent 3691b94 commit e13ccfa
Show file tree
Hide file tree
Showing 4 changed files with 145 additions and 95 deletions.
141 changes: 80 additions & 61 deletions lib/mongoAdapter.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
'use strict';

const {
_, Promise,
} = require( 'diaspora/lib/dependencies' );
const DiasporaAdapter = require( 'diaspora/lib/adapters/baseAdapter' );
const MongoEntity = require('./mongoEntity')
const MongoEntity = require('./mongoEntity');
const MongoClient = require( 'mongodb' ).MongoClient;
const Diaspora = require( 'diaspora' );

// Your adapter logic.

Expand All @@ -25,17 +30,21 @@ class MongoDiasporaAdapter extends DiasporaAdapter {
* @param {string} config.username=false - Username used to connect.
* @param {string|false} [config.password=false] - Password used to connect. Set to false to disable password authentication.
*/
constructor() {
super( MongoEntity, {
constructor(config) {
super( MongoEntity );
this.remaps = {
id: '_id',
}, {
};
this.remapsInverted = _.invert(this.remaps);
this.filters = {
input: {
id: val => new require( 'mongodb' ).ObjectID( val ),
},
output: {
_id: val => val.toString(),
},
});
};

if ( !config.hasOwnProperty( 'database' )) {
throw new Error( 'Missing required string parameter "database".' );
}
Expand All @@ -55,6 +64,7 @@ class MongoDiasporaAdapter extends DiasporaAdapter {
const authPrefix = ( false !== config.username ? `${ config.username + ( false !== config.password ? `:${ config.password }` : '' ) }@` : '' );
// Connection URL
const url = `mongodb://${ authPrefix }${ config.host }:${ config.port }/${ config.database }`;
Diaspora.logger.verbose(`Mongo connection URL:`, {url : url.replace( `${config.username}:${config.password}@`, `${config.username}:******` )});

// Use connect method to connect to the server
MongoClient.connect( url, otherProps, ( err, db ) => {
Expand Down Expand Up @@ -83,6 +93,38 @@ class MongoDiasporaAdapter extends DiasporaAdapter {
this.state = 'disconnected';
}

normalizeQueryMongo(query){
const newQuery = {};
_.forEach(query, (propQuery, propName) => {
_.forEach(propQuery, (value, key) => {
switch(key){
case '$equal':{
newQuery[propName] = {$eq: value};
} break;
case '$diff':{
newQuery[propName] = {$ne: value, $exists: true};
} break;
case '$lessEqual':{
newQuery[propName] = {$lte: value};
} break;
case '$greaterEqual':{
newQuery[propName] = {$gte: value};
} break;
case '$less':{
newQuery[propName] = {$lt: value};
} break;
case '$greater':{
newQuery[propName] = {$gt: value};
} break;
default: {
newQuery[propName] = { [key]: value};
} break;
}
});
});
return newQuery;
}

/**
* Insert a single entity in the memory store.
*
Expand All @@ -96,24 +138,15 @@ class MongoDiasporaAdapter extends DiasporaAdapter {
insertOne( table, entity ) {
entity = _.pickBy( entity, v => 'undefined' !== typeof v );
const collection = this.db.collection( table );
entity = this.remapInput( table, entity );
return collection.insertOne( entity ).then( res => {
const newDoc = _.first( res.ops );
return this.updateOne(
table,
{
_id: newDoc._id,
},
{
'$set': {
idHash: _.assign({}, newDoc.idHash, {
[this.name]: newDoc._id.toString(),
}),
},
},
{
remapInput: false,
}
{ _id: newDoc._id },
{ $set: { [_.get(this, 'remaps.idHash', 'idHash')]: _.assign({}, newDoc.idHash, {
[this.name]: newDoc._id.toString(),
}) } },
{ remapInput: false, mongoConvertQuery: false }
);
});
}
Expand All @@ -133,24 +166,17 @@ class MongoDiasporaAdapter extends DiasporaAdapter {
* @returns {Promise} Promise resolved once item is found. Called with (*{@link InMemoryEntity}* `entity`)
*/
findOne( table, queryFind, options = {}) {
options = this.normalizeOptions( options );
if ( true === options.remapInput ) {
queryFind = this.remapInput( table, queryFind );
}
queryFind = this.normalizeQuery( queryFind, options );
// Create a new query object
const redefinedQueryFind = {};
_.forEach( queryFind, ( val, key ) => {
if ( 'undefined' === val ) {
redefinedQueryFind[key] = {
$exists: false,
};
} else {
redefinedQueryFind[key] = val;
}
});
const queryOpts = _.pick(options, ['skip', 'limit']);
if(_.get(options, 'mongoConvertQuery', true)){
queryFind = this.normalizeQueryMongo(queryFind);
}
// console.log({queryFind, queryFind, options, queryOpts});
const collection = this.db.collection( table );
let promise = collection.findOne( redefinedQueryFind, options ).then( foundItem => {
let promise = collection.findOne( queryFind, queryOpts ).then( foundItem => {
if(_.isNil(foundItem)){
return Promise.resolve();
}
return Promise.resolve( options.remapOutput ? this.remapOutput( table, foundItem ) : foundItem );
});
return promise;
Expand Down Expand Up @@ -196,27 +222,25 @@ class MongoDiasporaAdapter extends DiasporaAdapter {
* @returns {Promise} Promise resolved once update is done. Called with (*{@link MongoEntity}* `entity`)
*/
updateOne( table, queryFind, update, options = {}) {
options = this.normalizeOptions( options );
if ( true === options.remapInput ) {
queryFind = this.remapInput( table, queryFind );
update = this.remapInput( table, update );
update = this.filterUpdateUnset( update );
}
queryFind = this.normalizeQuery( queryFind, options );
const collection = this.db.collection( table );
const subOptions = _.assign( options, {
remapInput: false,
remapOutput: false,
});
if(_.get(options, 'mongoConvertQuery', true)){
update = this.filterUpdateUnset(update);
}
return this.findOne( table, queryFind, subOptions ).then( foundItem => {
return collection.updateOne({
_id: foundItem._id,
}, update, subOptions ).then(() => Promise.resolve( foundItem._id ));
}).then( updatedId => this.findOne( table, {
_id: updatedId,
}, _.assign( subOptions, {
remapOutput: true,
})));
}).then( updatedId => {
return this.findOne( table, {
_id: { $eq: updatedId },
}, _.assign( subOptions, {
remapOutput: true,
}));
});
}

/**
Expand All @@ -232,18 +256,14 @@ class MongoDiasporaAdapter extends DiasporaAdapter {
* @returns {Promise} Promise resolved once update is done. Called with (*{@link MongoEntity}[]* `entities`)
*/
updateMany( table, queryFind, update, options = {}) {
options = this.normalizeOptions( options );
if ( true === options.remapInput ) {
queryFind = this.remapInput( table, queryFind );
update = this.remapInput( table, update );
}
queryFind = this.normalizeQuery( queryFind, options );
update = this.filterUpdateUnset( update );
const collection = this.db.collection( table );
const subOptions = _.assign( options, {
remapInput: false,
remapOutput: false,
});
if(_.get(options, 'mongoConvertQuery', true)){
update = this.filterUpdateUnset(update);
}
return this.findMany( table, queryFind, subOptions ).map( foundItem => {
return collection.updateOne({
_id: foundItem._id,
Expand Down Expand Up @@ -274,12 +294,10 @@ class MongoDiasporaAdapter extends DiasporaAdapter {
* @returns {Promise} Promise resolved once item is deleted. Called with (*undefined*)
*/
deleteOne( table, queryFind, options = {}) {
options = this.normalizeOptions( options );
if ( true === options.remapInput ) {
queryFind = this.remapInput( table, queryFind );
}
queryFind = this.normalizeQuery( queryFind, options );
const collection = this.db.collection( table );
if(_.get(options, 'mongoConvertQuery', true)){
queryFind = this.normalizeQueryMongo(queryFind);
}
return collection.deleteOne( queryFind, options ).then( results => Promise.resolve());
}

Expand All @@ -295,8 +313,9 @@ class MongoDiasporaAdapter extends DiasporaAdapter {
* @returns {Promise} Promise resolved once item is deleted. Called with (*undefined*)
*/
deleteMany( table, queryFind, options = {}) {
options = this.normalizeOptions( options );
queryFind = this.normalizeQuery( queryFind, options );
const subOptions = _.assign( options, {
remapOutput: false,
});
return this.findMany( table, queryFind, options ).then( found => {
const collection = this.db.collection( table );
return collection.deleteMany({
Expand Down
68 changes: 34 additions & 34 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
{
"name": "diaspora-mongo",
"version": "0.0.1",
"description": "MongoDB adapter for Diaspora",
"main": "index.js",
"directories": {
"lib": "lib"
},
"scripts": {
"test": "mocha test/index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/GerkinDev/Diaspora-Mongo.git"
},
"keywords": [
"MongoDB",
"Diaspora",
"adapter"
],
"author": "Gerkin",
"license": "MIT",
"bugs": {
"url": "https://github.com/GerkinDev/Diaspora-Mongo/issues"
},
"homepage": "https://github.com/GerkinDev/Diaspora-Mongo#readme",
"dependencies": {
"mongodb": "^2.2.31"
},
"devDependencies": {
"diaspora": "git+ssh://[email protected]/GerkinDev/Diaspora.git"
},
"peerDependencies": {
"diaspora": ">= 0.2.x"
}
"name": "diaspora-mongo",
"version": "0.0.1",
"description": "MongoDB adapter for Diaspora",
"main": "index.js",
"directories": {
"lib": "lib"
},
"scripts": {
"test": "mocha test/index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/GerkinDev/Diaspora-Mongo.git"
},
"keywords": [
"MongoDB",
"Diaspora",
"adapter"
],
"author": "Gerkin",
"license": "MIT",
"bugs": {
"url": "https://github.com/GerkinDev/Diaspora-Mongo/issues"
},
"homepage": "https://github.com/GerkinDev/Diaspora-Mongo#readme",
"dependencies": {
"mongodb": "^2.2.31"
},
"devDependencies": {
"diaspora": "ssh+git://[email protected]:GerkinDev/Diaspora.git"
},
"peerDependencies": {
"diaspora": ">= 0.2.x"
}
}
16 changes: 16 additions & 0 deletions test/adapters/mongo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use strict';

const AdapterTestUtils = require( 'diaspora/test/adapters/utils' );
const ADAPTER_LABEL = 'mongo';

const adapter = AdapterTestUtils.createDataSource( ADAPTER_LABEL, {database: 'diasporaMongoTest'});
console.log(adapter)
adapter.waitReady().then(() => {
adapter.db.dropCollection('test');
adapter.db.dropCollection('app1-matchmail-simple');
}).catch(() => Promise.resolve());

AdapterTestUtils.checkSpawnedAdapter( ADAPTER_LABEL, 'Mongo' );
AdapterTestUtils.checkEachStandardMethods( ADAPTER_LABEL );
AdapterTestUtils.checkApplications( ADAPTER_LABEL );
AdapterTestUtils.checkRegisterAdapter( ADAPTER_LABEL, 'mongo' );
15 changes: 15 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

/* globals l: false, it: false, describe: false, require: false, expect: false, Diaspora: false, getStyle: false, importTest: false */

require( 'diaspora/test/defineGlobals' );
require( '../index' );

if ( 'no' === process.env.SAUCE || 'undefined' === typeof process.env.SAUCE ) {
if ( !process.browser ) {
global.Diaspora = require( 'diaspora' );
}
global.dataSources = {};

importTest( getStyle( 'category', 'Adapters' ), `${ __dirname }/adapters/mongo.js` );
}

0 comments on commit e13ccfa

Please sign in to comment.