scottwrobinson / camo

A class-based ES6 ODM for Mongo-like databases.
556 stars 80 forks source link

Fixed #111 by conditionally requiring the nedb and mongo clients. #116

Open stevefranchak opened 6 years ago

stevefranchak commented 6 years ago

I ran into #111 while developing an Electron application that is only going to use nedb. I installed camo with npm install --no-optional camo since my application directly depends on nedb and I did not want mongodb and its dependencies (like kerberos) to be installed. I received a similar error to what is provided in #111.

I fixed this by conditionally requiring the nedb and mongo clients in lib/db.js. With this change, the aforementioned error will only be thrown if the user intentionally tries to use one of the client databases whose corresponding module is not installed.

I did not provide tests as I did not know if it matters that the unit tests fail for a --no-optional installation.

I started playing with the idea of allowing unit tests to pass if either the nedb or mongodb modules were not detected (depending on the test), but then realized this may not be wanted or needed. I tried out the idea of figuring out whether to call describe or describe.skip based on whether a callback function that contains require calls throws an error. Before that approach, I tried calling this.skip() inside of before() hooks, but this did not seem to work (probably because camo's version of mocha is < 3).

Example:

In test/util.js:

// Skips entire test suite if the callback 'tryRequires' throws an error.
exports.maybeDescribe = function(tryRequires = () => {}) {
  let maybeDescribe = this;
  try {
    tryRequires();
  } catch(err) {
    maybeDescribe = this.skip;
  }
  return maybeDescribe;
}

In test/mongoclient.test.js:

const maybeDescribe = require('./util').maybeDescribe;
let ObjectId; // changed from const

// I had to pass the 'describe' in this context since
// it did not equal require('mocha').describe in test/util.js.
// TODO: look into this further 
maybeDescribe.call(describe, () => {
    ObjectID = require('mongodb').ObjectId;
})('MongoClient', function() {
// . . . .
});

Feedback on how to go about providing unit tests if they're needed for this fix would be much appreciated.