Skip to content

Commit

Permalink
Allow property style access of all collections through the mongoist p…
Browse files Browse the repository at this point in the history
…roxy, with the exception of those that have the same name as a db function (closes #17)

* This is a breaking change for anyone intentionally accessing Database properties (connectionString, options, connection, features, client) through the proxy
  • Loading branch information
Shil Sinha authored and saintedlama committed Jun 4, 2018
1 parent b84bec2 commit 80d1cd4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
18 changes: 13 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,30 @@ const Collection = require('./lib/collection');
const Cursor = require('./lib/cursor');
const Bulk = require('./lib/bulk');

function isValidCollectionName(name) {
return typeof name === 'string' && name &&
!(name.includes('$') || name.includes('\0') || name.startsWith('system.'));
}

module.exports = function(connectionString, options) {
const db = new Database(connectionString, options);
const dbMethods = Object.create(null);

return new Proxy(db, {
get: function(obj, prop) {
const dbProp = obj[prop];

if (dbProp !== undefined) {
return dbProp;
if (typeof dbProp === 'function') {
//lazily cache function bound to underlying db
dbMethods[prop] = dbMethods[prop] || dbProp.bind(db);
return dbMethods[prop];
}

if (typeof prop === 'symbol') {
return db[prop];
if (isValidCollectionName(prop)) {
return db.collection(prop);
}

return db.collection(prop);
return dbProp;
}
});
}
Expand Down
9 changes: 7 additions & 2 deletions test/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,13 @@ describe('database', function() {

afterEach(() => db.close());

it('should return a collection if accessing a non defined property', async() => {
expect(db.xyz).to.exist;
it('should return a collection if accessing a property that is a valid collection name', async() => {
expect(await db.xyz.count()).to.equal(0);
expect(await db.features.count()).to.equal(0);
expect(await db.options.count()).to.equal(0);
expect(await db.client.count()).to.equal(0);
expect(await db.connection.count()).to.equal(0);
expect(await db.domain.count()).to.equal(0);
});

it('should accept connection strings without mongodb:// protocol specified', async() => {
Expand Down

0 comments on commit 80d1cd4

Please sign in to comment.