Skip to content

Commit

Permalink
fix(ReadPreference): only allow valid ReadPreference modes
Browse files Browse the repository at this point in the history
Fixes NODE-1425
  • Loading branch information
kvwalker authored and daprahamian committed Aug 13, 2019
1 parent ff7166d commit 06bbef2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/core/topologies/read_preference.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
* @return {ReadPreference}
*/
const ReadPreference = function(mode, tags, options) {
if (!ReadPreference.isValid(mode)) {
throw new TypeError(`provided mode ${mode} is an invalid ReadPreference mode`);
}

// TODO(major): tags MUST be an array of tagsets
if (tags && !Array.isArray(tags)) {
console.warn(
Expand Down Expand Up @@ -43,7 +47,7 @@ const ReadPreference = function(mode, tags, options) {
this.minWireVersion = 5;
}

if (this.mode === ReadPreference.PRIMARY || this.mode === true) {
if (this.mode === ReadPreference.PRIMARY) {
if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) {
throw new TypeError('Primary read preference cannot be combined with tags');
}
Expand Down Expand Up @@ -77,8 +81,8 @@ const VALID_MODES = [
ReadPreference.SECONDARY,
ReadPreference.SECONDARY_PREFERRED,
ReadPreference.NEAREST,
true,
false,
// true,
// false,
null
];

Expand Down
15 changes: 15 additions & 0 deletions test/functional/readpreference_tests.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';
var test = require('./shared').assert;
var setupDatabase = require('./shared').setupDatabase;
const expect = require('chai').expect;

describe('ReadPreference', function() {
before(function() {
Expand Down Expand Up @@ -546,4 +547,18 @@ describe('ReadPreference', function() {
});
}
});

it('Should throw an error on an invalid readPreference', function(done) {
const configuration = this.configuration;

const client = configuration.newClient();
client.connect((err, client) => {
const db = client.db(configuration.db);
expect(db.collection.bind(db, 'test', { readPreference: 'invalid' })).to.throw(
'provided mode invalid is an invalid ReadPreference mode'
);
client.close();
done();
});
});
});

0 comments on commit 06bbef2

Please sign in to comment.